OC高效率52之儘可能使用不可變對象

#import <Foundation/Foundation.h>

@interface EOCPointOfInterest : NSObject
/**
 *  1.在編程實踐中,則應該儘可能把對外公佈出來的屬性設爲只,讀,並且只在確有必要時纔將屬性對外公佈
 *  2.不可變的類,須要把全部屬性聲明爲readonly
 *  3.對象外部,仍能經過「鍵值編碼設置屬性值kvc」 [pointOfInterest setValue:@"abc" forkey:@"identifier"]
 */
@property (nonatomic , copy , readonly) NSString *identifier;
@property (nonatomic , copy , readonly) NSString *title;
@property (nonatomic , assign , readonly) float latitude;
@property (nonatomic , assign , readonly) float longitude;
-(id) initWithIdentifier:(NSString *)identifier
                   title:(NSString *)title
                latitude:(float)latitude
               longitude:(float) longitude;
@end
#import "EOCPointOfInterest.h"

@implementation EOCPointOfInterest

@end
#import "EOCPointOfInterest.h"
/**
 *  在分類中把屬性擴展爲讀寫
 */
@interface EOCPointOfInterest (EOCPointOfInterest)

@property (nonatomic , copy , readwrite) NSString *identifier;
@property (nonatomic , copy , readwrite) NSString *title;
@property (nonatomic , assign , readwrite) float latitude;
@property (nonatomic , assign , readwrite) float longitude;
@end
#import "EOCPointOfInterest+EOCPointOfInterest.h"

@implementation EOCPointOfInterest (EOCPointOfInterest)

@end
#import <Foundation/Foundation.h>

@interface EOCPerson : NSObject
@property (nonatomic , copy , readonly) NSString *firstName;
@property (nonatomic , copy , readonly) NSString *lastName;
@property (nonatomic , strong , readonly) NSSet *friends;

-(id)initWithFirstName:(NSString *)firstName
           andLastName:(NSString *)lastName;

-(void)addFriend:(EOCPerson *)person;
-(void)removeFriend:(EOCPerson *)person;
@end
#import "EOCPerson.h"
@interface EOCPerson ()
@property (nonatomic , copy , readwrite) NSString *firstName;
@property (nonatomic , copy , readwrite) NSString *lastName;
@end


@implementation EOCPerson
{
    NSMutableSet *_internalFriend;
}
-(NSSet *)friends{
    return [_internalFriend copy];
}
-(void) addFriend:(EOCPerson *)person{
    [_internalFriend addObject:person];
}
-(void) removeFriend:(EOCPerson *)person
{
    [_internalFriend removeObject:person];
}
-(id)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName{

    if ((self = [super init])){
        _firstName = firstName;
        _lastName = lastName;
        _internalFriend = [[NSMutableSet alloc]init];
    
    }
    return self;
}
@end
相關文章
相關標籤/搜索