【发布时间】:2009-11-26 10:56:58
【问题描述】:
我为 iPhone 开发工作了一段时间。第一次,我对 Objective-c 中的内存管理感到非常惊讶 :)。但现在我明白了一点。
问题是,有时我将协议用作类的属性,因为我认为它的定义与 C# 或 Java 中的“接口”非常相似。如下所示。
@protocol Shield
...
@end
// Interface
@interface Dragon {
id<Shield> shield
NSString * name;
}
@property (nonatomic,retain) id<Shield> shield;
@property (nonatomic,retain) NSString * name;
@end
但我总是在 dealloc() 方法中释放任何属性对象。如下所示。
-(void)dealloc {
[name release];
[shield release]; // <--- Totally impossible. xcode said '-release not found in protocol'
[super dealloc];
}
如您所见,我无法发布协议。那么这会导致我未来的记忆问题吗?你有其他方法来处理这个解决方案来给我建议吗?
【问题讨论】:
-
iKenndac 下面的回答是正确的方法。或者,您可以将 ID 转换为符合 NSObject 协议的 ID 并调用 release 方法。
[(id<NSObject)shield release]或 NSObject[(NSObject*)shield release]
标签: iphone objective-c protocols