327

是否可以使用标准属性语法将块作为属性?

ARC有什么变化吗?

4

8 回答 8

315
@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;
于 2012-10-23T15:20:35.587 回答
210

以下是如何完成此类任务的示例:

#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

于 2010-10-14T17:09:29.467 回答
160

@property(复制)无效

@property (copy)void (^doStuff)(void);

就是这么简单。

这是实际的 Apple 文档,它准确地说明了要使用的内容:

苹果多可。

您的 .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+) 系统,执行此处显示的操作。就是这么简单。

于 2013-12-24T12:02:10.780 回答
20

为了后代/完整性......这里有两个完整的例子,说明如何实现这种可笑的多功能“做事方式”。@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

愚蠢的?是的。 有用?地狱是的。 这是设置属性的另一种“更原子”的方式......以及一个非常有用的类......</p>

@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 内部,这是一个值得商榷的冒险实践..)与第一个示例的“非原子”“getter”机制。在任何一种情况下......“硬编码”实现总是可以被覆盖,每个实例.. a lá..

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]; 
};

这种模式可以在Cocoa API中反复应用。使用属性将代码的相关部分更紧密地结合在一起,消除复杂的委托范式,并利用对象的强大功能,而不仅仅是充当愚蠢的“容器”。

于 2013-05-31T21:11:28.527 回答
8

当然,您可以使用块作为属性。但请确保它们被声明为@property(copy)。例如:

typedef void(^TestBlock)(void);

@interface SecondViewController : UIViewController
@property (nonatomic, copy) TestBlock block;
@end

在 MRC 中,捕获上下文变量的块被分配在堆栈中;当堆栈帧被销毁时,它们将被释放。如果它们被复制,则会在heap中分配一个新块,稍后可以在弹出堆栈帧后执行该块。

于 2015-07-16T09:08:50.417 回答
6

免责声明

这不是“好的答案”,因为这个问题明确要求 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,针对闭包进行了优化

由于 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!")
    }
}
于 2014-06-17T13:46:08.990 回答
-1

你好,斯威夫特

补充@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)
于 2014-07-21T17:56:53.583 回答
-4

您可以遵循以下格式,并可以testingObjectiveCBlock在类中使用该属性。

typedef void (^testingObjectiveCBlock)(NSString *errorMsg);

@interface MyClass : NSObject
@property (nonatomic, strong) testingObjectiveCBlock testingObjectiveCBlock;
@end

欲了解更多信息,请查看这里

于 2014-01-24T06:41:20.500 回答