我可以将Objective-C块作为属性吗?
-
30-09-2019 - |
题
是否可以使用标准属性语法将块作为属性?
有什么变化 弧?
解决方案
@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;
其他提示
这是您如何完成此类任务的一个示例:
#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)()
. 。如果您需要传递两个对象,请将其更改为: typedef int (^IntBlock)(id, id)
, ,并将您的块更改为:
^ (id obj1, id obj2)
{
return rand();
};
我希望这有帮助。
编辑2012年3月12日:
对于ARC,不需要具体的更改,因为ARC将为您管理块,只要将它们定义为副本即可。您也不需要将属性设置为零件中的零。
有关更多阅读,请查看此文档: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();
}
提防过时的示例代码。
使用Modern(2014+)系统,请在此处显示。这很简单。希望它能帮助某人。 2013年圣诞快乐!
为了后代 /完整性的缘故……这是如何实现这种可笑的“做事方式”的两个完整示例。 @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
这说明了通过登录器设置块属性(尽管Inside Inter,这是一个有争议的dicey练习。)v和第一个示例的“非原子”“ getter”机制。无论哪种情况……“硬编码”的实现总是可以被覆盖, 每个实例..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];
};
可以应用此模式 一遍又一遍地 可可API。使用属性带来代码的相关部分 走得更近, , 排除 复杂的代表团范例, ,并利用仅充当愚蠢的“容器”之外的物体的力量。
当然,您可以将块用作属性。但请确保它们被宣布为 @property(复制). 。例如:
typedef void(^TestBlock)(void);
@interface SecondViewController : UIViewController
@property (nonatomic, copy) TestBlock block;
@end
在MRC中,捕获上下文变量的块分配 堆;当堆栈框架被销毁时,它们将被释放。如果复制它们,将分配一个新块 堆, ,可以在弹出堆栈框架后稍后执行。
委员会
这并不是为了“好的答案”,因为这个问题明确要求Objectivec。当苹果在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" })
尾随
此特殊情况仅在块是最后一个参数时才有效 尾随
这是一个示例(与推断签名合并以显示快速力量)
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)
您可以遵循下面的格式,可以使用 testingObjectiveCBlock
班上的属性。
typedef void (^testingObjectiveCBlock)(NSString *errorMsg);
@interface MyClass : NSObject
@property (nonatomic, strong) testingObjectiveCBlock testingObjectiveCBlock;
@end
有关更多信息,请查看 这里