为什么Objective-C属性不方便?

时间:2022-09-07 11:20:36

It is more of a complain than a question, though maybe someone has some good points on it. So basically if you want an ivar in your Objective-C class have accessor-methods you have to mention it 3 times

这与其说是一个问题,不如说是一个抱怨,尽管也许有人对此有一些好的看法。基本上,如果你想要Objective-C类中的ivar有访问器-方法你必须提到它三次

SomeClass* _ivar;
@property (nonatomic,retain/assign/copy) SomeClass* ivar;
@synthesize ivar = _ivar;

and maybe 4th time in dealloc method. So wouldn't it be more convenient if the approach would be like Java-style annotations - in one place before the actual ivar declaration, just something like:

也许是第四次用dealloc方法。因此,如果这种方法类似于java风格的注释——在实际的ivar声明之前的一个地方,就像:

@property (nonatomic,retain,synthesize = ivar,dealloc) SomeClass* _ivar; 

this also generates accessor methods, and dealloc - telling to dealloc the ivar in dealloc method.

这也会生成访问器方法,并在dealloc方法中对ivar进行dealloc -告诉。

2 个解决方案

#1


6  

Actually you don't have to declare ivar - they can be synthesized if you just declare property for them. This should synthesize name iVar for you: (not supported in legacy run-times though - so one of the reasons of this seemingly redundant syntax is for backward compatibility with legacy platforms)

实际上你不需要声明ivar -只要声明属性就可以合成它们。这应该为您合成name iVar:(虽然在遗留运行时中不支持——因此这种看似冗余的语法的原因之一是为了与遗留平台向后兼容)

@interface MyClass : NSObject 
{
}

@property(copy) NSString *name;

@end

...
@synthesize name;

In new XCode version (4.0 probably) you won't need to use @synthesize as well - properties will be synthesized by default.

在新的XCode版本(可能是4.0版本)中,您不需要使用@synthesize,默认情况下将合成属性。

So as you see objective-c develops to satisfy your wishes :)

所以当你看到objective-c的发展是为了满足你的愿望

#2


0  

Xcode 4 doesn't automatically synthesize properties unfortunately. But with ARC (automatic reference counting) you no longer need to worry about dealloc and instance variables anymore.

不幸的是,Xcode 4不会自动合成属性。但是使用ARC(自动引用计数),您不再需要担心dealloc和实例变量。

#1


6  

Actually you don't have to declare ivar - they can be synthesized if you just declare property for them. This should synthesize name iVar for you: (not supported in legacy run-times though - so one of the reasons of this seemingly redundant syntax is for backward compatibility with legacy platforms)

实际上你不需要声明ivar -只要声明属性就可以合成它们。这应该为您合成name iVar:(虽然在遗留运行时中不支持——因此这种看似冗余的语法的原因之一是为了与遗留平台向后兼容)

@interface MyClass : NSObject 
{
}

@property(copy) NSString *name;

@end

...
@synthesize name;

In new XCode version (4.0 probably) you won't need to use @synthesize as well - properties will be synthesized by default.

在新的XCode版本(可能是4.0版本)中,您不需要使用@synthesize,默认情况下将合成属性。

So as you see objective-c develops to satisfy your wishes :)

所以当你看到objective-c的发展是为了满足你的愿望

#2


0  

Xcode 4 doesn't automatically synthesize properties unfortunately. But with ARC (automatic reference counting) you no longer need to worry about dealloc and instance variables anymore.

不幸的是,Xcode 4不会自动合成属性。但是使用ARC(自动引用计数),您不再需要担心dealloc和实例变量。