是否可以使用标准属性语法将块作为属性?
ARC是否有任何更改?
是否可以使用标准属性语法将块作为属性?
ARC是否有任何更改?
Answers:
@property (nonatomic, copy) void (^simpleBlock)(void);
@property (nonatomic, copy) BOOL (^blockWithParamter)(NSString *input);
如果要在多个位置重复相同的块,请使用def类型
typedef void(^MyCompletionBlock)(BOOL success, NSError *error);
@property (nonatomic) MyCompletionBlock completion;
@synthesize myProp = _myProp
@synthesize
使用默认设置,那么您正在做什么@synthesize name = _name;
stackoverflow.com/a/12119360/1052616
这是您如何完成此任务的示例:
#import <Foundation/Foundation.h>
typedef int (^IntBlock)();
@interface myobj : NSObject
{
IntBlock compare;
}
@property(readwrite, copy) IntBlock compare;
@end
@implementation myobj
@synthesize compare;
- (void)dealloc
{
// need to release the block since the property was declared copy. (for heap
// allocated blocks this prevents a potential leak, for compiler-optimized
// stack blocks it is a no-op)
// Note that for ARC, this is unnecessary, as with all properties, the memory management is handled for you.
[compare release];
[super dealloc];
}
@end
int main () {
@autoreleasepool {
myobj *ob = [[myobj alloc] init];
ob.compare = ^
{
return rand();
};
NSLog(@"%i", ob.compare());
// if not ARC
[ob release];
}
return 0;
}
现在,如果您需要更改比较类型,则唯一需要更改的就是typedef int (^IntBlock)()
。如果需要向其传递两个对象,请将其更改为this typedef int (^IntBlock)(id, id)
,然后将块更改为:
^ (id obj1, id obj2)
{
return rand();
};
我希望这有帮助。
编辑2012年3月12日:
对于ARC,不需要任何特定更改,因为只要将块定义为副本,ARC就会为您管理块。您也不需要在析构函数中将属性设置为nil。
有关更多阅读,请查看此文档:http : //clang.llvm.org/docs/AutomaticReferenceCounting.html
对于Swift,只需使用闭包:示例。
在Objective-C中:
@property (copy)void (^doStuff)(void);
就这么简单。
在您的.h文件中:
// Here is a block as a property:
//
// Someone passes you a block. You "hold on to it",
// while you do other stuff. Later, you use the block.
//
// The property 'doStuff' will hold the incoming block.
@property (copy)void (^doStuff)(void);
// Here's a method in your class.
// When someone CALLS this method, they PASS IN a block of code,
// which they want to be performed after the method is finished.
-(void)doSomethingAndThenDoThis:(void(^)(void))pleaseDoMeLater;
// We will hold on to that block of code in "doStuff".
这是您的.m文件:
-(void)doSomethingAndThenDoThis:(void(^)(void))pleaseDoMeLater
{
// Regarding the incoming block of code, save it for later:
self.doStuff = pleaseDoMeLater;
// Now do other processing, which could follow various paths,
// involve delays, and so on. Then after everything:
[self _alldone];
}
-(void)_alldone
{
NSLog(@"Processing finished, running the completion block.");
// Here's how to run the block:
if ( self.doStuff != nil )
self.doStuff();
}
对于现代(2014+)系统,请执行此处显示的操作。就这么简单。
strong
代替copy
?
nonatomic
大多数其他使用属性的情况下,属性不应与最佳做法不同?
为了后代/完整性的考虑,这是两个完整的示例,说明如何实现这种可笑的通用“做事方式”。@Robert的答案非常简洁和正确,但是在这里我还想展示实际“定义”块的方法。
@interface ReusableClass : NSObject
@property (nonatomic,copy) CALayer*(^layerFromArray)(NSArray*);
@end
@implementation ResusableClass
static NSString const * privateScope = @"Touch my monkey.";
- (CALayer*(^)(NSArray*)) layerFromArray {
return ^CALayer*(NSArray* array){
CALayer *returnLayer = CALayer.layer
for (id thing in array) {
[returnLayer doSomethingCrazy];
[returnLayer setValue:privateScope
forKey:@"anticsAndShenanigans"];
}
return list;
};
}
@end
愚蠢?是。 有用?地狱是的。 这是设置属性的另一种“更原子”的方法..和一个非常有用的类……
@interface CALayoutDelegator : NSObject
@property (nonatomic,strong) void(^layoutBlock)(CALayer*);
@end
@implementation CALayoutDelegator
- (id) init {
return self = super.init ?
[self setLayoutBlock: ^(CALayer*layer){
for (CALayer* sub in layer.sublayers)
[sub someDefaultLayoutRoutine];
}], self : nil;
}
- (void) layoutSublayersOfLayer:(CALayer*)layer {
self.layoutBlock ? self.layoutBlock(layer) : nil;
}
@end
这说明了与第一个示例的“非原子”“获取”机制相比,通过访问器(尽管在init中,有争议的实践)设置了块属性。无论哪种情况,“硬编码”实现总是可以被实例覆盖,例如。
CALayoutDelegator *littleHelper = CALayoutDelegator.new;
littleHelper.layoutBlock = ^(CALayer*layer){
[layer.sublayers do:^(id sub){ [sub somethingElseEntirely]; }];
};
someLayer.layoutManager = littleHelper;
另外..如果您想在类别中添加块属性...说您想使用块而不是一些老式的目标/动作“动作” ...您可以仅使用关联的值。关联块。
typedef void(^NSControlActionBlock)(NSControl*);
@interface NSControl (ActionBlocks)
@property (copy) NSControlActionBlock actionBlock; @end
@implementation NSControl (ActionBlocks)
- (NSControlActionBlock) actionBlock {
// use the "getter" method's selector to store/retrieve the block!
return objc_getAssociatedObject(self, _cmd);
}
- (void) setActionBlock:(NSControlActionBlock)ab {
objc_setAssociatedObject( // save (copy) the block associatively, as categories can't synthesize Ivars.
self, @selector(actionBlock),ab ,OBJC_ASSOCIATION_COPY);
self.target = self; // set self as target (where you call the block)
self.action = @selector(doItYourself); // this is where it's called.
}
- (void) doItYourself {
if (self.actionBlock && self.target == self) self.actionBlock(self);
}
@end
现在,当您按下按钮时,您无需设置任何IBAction
戏剧性内容。只需将要创建的工作关联起来...
_button.actionBlock = ^(NSControl*thisButton){
[doc open]; [thisButton setEnabled:NO];
};
这种模式可以OVER和OVER应用于 Cocoa API。使用属性可以使代码的相关部分更紧密地结合在一起,消除复杂的委托范式,并充分利用对象的功能,而不仅仅是充当愚蠢的“容器”。
当然,您可以将块用作属性。但是请确保将它们声明为@property(copy)。例如:
typedef void(^TestBlock)(void);
@interface SecondViewController : UIViewController
@property (nonatomic, copy) TestBlock block;
@end
在MRC中,捕获上下文变量的块在堆栈中分配;当堆栈框架被破坏时,它们将被释放。如果将它们复制,则会在heap中分配一个新块,可以在弹出堆栈帧之后稍后执行。
这并不是“好的答案”,因为此问题明确要求ObjectiveC。当Apple在WWDC14上介绍Swift时,我想分享在Swift中使用块(或闭包)的不同方法。
您提供了许多方法来传递等效于Swift中功能的块。
我发现了三个。
为了理解这一点,我建议您在操场上测试一下这小段代码。
func test(function:String -> String) -> String
{
return function("test")
}
func funcStyle(s:String) -> String
{
return "FUNC__" + s + "__FUNC"
}
let resultFunc = test(funcStyle)
let blockStyle:(String) -> String = {s in return "BLOCK__" + s + "__BLOCK"}
let resultBlock = test(blockStyle)
let resultAnon = test({(s:String) -> String in return "ANON_" + s + "__ANON" })
println(resultFunc)
println(resultBlock)
println(resultAnon)
由于Swift已针对异步开发进行了优化,因此Apple在闭包方面的工作更多。首先是可以推断函数签名,因此您不必重写它。
let resultShortAnon = test({return "ANON_" + $0 + "__ANON" })
let resultShortAnon2 = test({myParam in return "ANON_" + myParam + "__ANON" })
仅当块是最后一个参数时,此特殊情况才有效,这称为尾随闭包
这是一个示例(与推断的签名合并以显示Swift的功能)
let resultTrailingClosure = test { return "TRAILCLOS_" + $0 + "__TRAILCLOS" }
最后:
使用所有这些功能,我将混合尾随闭包和类型推断(命名以提高可读性)
PFFacebookUtils.logInWithPermissions(permissions) {
user, error in
if (!user) {
println("Uh oh. The user cancelled the Facebook login.")
} else if (user.isNew) {
println("User signed up and logged in through Facebook!")
} else {
println("User logged in through Facebook!")
}
}
你好,斯威夫特
补充@Francescu的回答。
添加额外的参数:
func test(function:String -> String, param1:String, param2:String) -> String
{
return function("test"+param1 + param2)
}
func funcStyle(s:String) -> String
{
return "FUNC__" + s + "__FUNC"
}
let resultFunc = test(funcStyle, "parameter 1", "parameter 2")
let blockStyle:(String) -> String = {s in return "BLOCK__" + s + "__BLOCK"}
let resultBlock = test(blockStyle, "parameter 1", "parameter 2")
let resultAnon = test({(s:String) -> String in return "ANON_" + s + "__ANON" }, "parameter 1", "parameter 2")
println(resultFunc)
println(resultBlock)
println(resultAnon)