OOP,目标 c 中的聚合
我有一些复杂的对象,我不想实现它并且稍后会出现内存泄漏,所以必须询问:) 这是进行聚合的好方法吗?我是否需要以及在哪里从用户中清除角色对象?
#import "Role.h"
@interface User : NSObject {
NSString *firstName;
NSString *lastName;
Role *role;
}
@property (nonatomic, retain) NSString *firstName;
@property (nonatomic, retain) NSString *lastName;
@property (nonatomic, retain) Role *role;
@end
#import "User.h"
@implementation User
@synthesize firstName;
@synthesize lastName;
@synthesize role;
@end
@interface Role : NSObject {
NSInteger *roleId;
NSString *title;
NSString *description;
}
@property (nonatomic, retain) NSInteger *roleId;
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *description;
@end
#import "Role.h"
@implementation Role
@synthesize roleId;
@synthesize title;
@synthesize description;
@end
I have some complex objects and I don't want to implement it and have memory leaks later, so must ask :)
Is this good way of doing aggregation? Do I need and where to clean Role object from User?
#import "Role.h"
@interface User : NSObject {
NSString *firstName;
NSString *lastName;
Role *role;
}
@property (nonatomic, retain) NSString *firstName;
@property (nonatomic, retain) NSString *lastName;
@property (nonatomic, retain) Role *role;
@end
#import "User.h"
@implementation User
@synthesize firstName;
@synthesize lastName;
@synthesize role;
@end
@interface Role : NSObject {
NSInteger *roleId;
NSString *title;
NSString *description;
}
@property (nonatomic, retain) NSInteger *roleId;
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *description;
@end
#import "Role.h"
@implementation Role
@synthesize roleId;
@synthesize title;
@synthesize description;
@end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 dealloc 方法需要如下所示:
对于用户:
对于角色:
roleId 不需要释放,因为 NSInteger 实际上是原始整数类型的 typedef。这也意味着你的属性声明是错误的,它应该是:
另外,NSString 是不可变的,它实现了复制协议,所以你的 NSString 属性应该是
copy
而不是retain
。例如编辑
正如 Björn 指出的,Role 的界面应该是:
Your dealloc methods need to look like the following:
For user:
For Role:
roleId does not need to be released because NSInteger is actually a typedef to a primitive integer type. That also means your property declaration is wrong, it should be:
Also, NSString is immutable and it implements the copying protocol so your NSString properties should be
copy
notretain
. e.g.Edit
As Björn points out, the interface for Role should be: