Eyes, JAPAN Blog > Effective Objective-C(1)

Effective Objective-C(1)

will

この記事は1年以上前に書かれたもので、内容が古い可能性がありますのでご注意ください。

From now on, I would like to start continuous blogs to describe how to programming in objective-c effectively.

Prefer Immutable Objects.

It is common to declare a property of a class as collection data type. It can be mutable or immutable. It is recommended to make this kind of property  readonly externally and readwrite internally to avoid directly modify the collection from outside.
Give an example as following:

@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;
@end

/ EOCPerson.m
#import "EOCPerson.h"
@interface EOCPerson ()
@property (nonatomic, copy, readwrite) NSString *firstName;
@property (nonatomic, copy, readwrite) NSString *lastName;
@end

@implementation EOCPerson
{
 NSMutableSet *_internalFriends;
}

- (NSSet*)friends
{
 return [_internalFriends copy];
}
- (void)addFriend:(EOCPerson*)person
{
 [_internalFriends addObject:person];
}
- (void)removeFriend:(EOCPerson*)person
{
 [_internalFriends removeObject:person];
}
- (id)initWithFirstName:(NSString*)firstName andLastName:(NSString*)lastName
{
 if ((self = [super init]))
 {
  _firstName = firstName;
  _lastName = lastName;
  _internalFriends = [NSMutableSet new];
 }
 return self;
}
@end

Why here in the method:

- (NSSet*)friends
{
return [_internalFriends copy];
}

using copy instead of just return _internalFriends, which can also return NSSet object. Because it makes outside modify the mutable set possible, see the following code

EOCPerson *person = /* ... */;
NSSet *friends = person.friends;
if ([friends isKindOfClass:[NSMutableSet class]]) {
NSMutableSet *mutableFriends = (NSMutableSet*)friends;
/* mutate the set */
}

In this code, if the function – (NSSet*)friends; only return NSMutableSet instead of copy, it make the code outside to modify the friends set.
Reference:

<Effective Objective-C 2.0: 52 Specific Ways to Improve Your iOS and OS X Programs> by Matt Galloway

  • このエントリーをはてなブックマークに追加

Comments are closed.