开发者

OOP, aggregation in objective c

开发者 https://www.devze.com 2023-02-03 15:14 出处:网络
I have some complex objects and I don\'t want to implement it and have memory leaks later, so must ask :)

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开发者_Python百科 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


Your dealloc methods need to look like the following:

For user:

-dealloc
{
    [firstName release];
    [lastName release];
    [role release];
    [super dealloc];
}

For Role:

-dealloc
{
    [title release];
    [description release];
    [super dealloc];
}

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:

@property (nonatomic, assign) NSInteger roleId;

Also, NSString is immutable and it implements the copying protocol so your NSString properties should be copy not retain. e.g.

@property (nonatomic, copy) NSString *firstName;

Edit

As Björn points out, the interface for Role should be:

@interface Role : NSObject {
    NSInteger roleId;  // not a pointer
    NSString *title;
    NSString *description;
}
@property (nonatomic, assign) NSInteger roleId;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *description;
@end
0

精彩评论

暂无评论...
验证码 换一张
取 消