Reputation: 3909
you have a class or ViewController using model/service class like so:
@interface MainViewController : UIViewController <TweetServiceDelegate> {
NSArray *_tweets;
}
@property (nonatomic, strong) TweetService *tweetService;
@end
@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.twitterService queryForLatestTweets];
}
// delegate methods the tweetservice calls back after async getting data
- (void)querySucceededWithTweets:(NSArray *)tweets {
_tweets = [tweets copy];
}
@end
The reason I ask because the Service has a weak reference to the delegate, which is the ViewController.
So I know with ARC you don't want 2 things that use each other to both have a strong reference, so if it's weak but the ViewController retains the NSArray, then the Service wouldn't be collected once it went out of scope, assuming the service did go out of scope but the ViewController didn't
@interface TweetService
@property (nonatomic, weak) id<TweetServiceDelegate> delegate;
@end
@implementation TweetService
- (void)queryForLatestTweets {
// do the query with AFNetworking, when succeed block fires, call the delegate
[self.delegate querySucceededWithTweets:arrayOfTweets];
}
@end
Upvotes: 0
Views: 83
Reputation: 794
I will say YES it is good to use because...
if you are not copying that array just simply assign _tweet = tweet array.
then if you are doing change in any one of the array it will affect to other array..
so Yes i will suggest you to use COPY method such time...
Thanks.
Upvotes: 0
Reputation: 1459
I would say this is rather the recommended way of doing this sort of things. The service is held strongly by the controller that needs it, but the service holds the controller only weakly as a delegate because it does not need to know what its delegate is -- or even if it exists -- to function.
When the service returns something through delegate methods back to its delegate, the delegate should claim ownership of the data. The preferred way is to copy
, since the delegate does not know anything about the return value's lifecycle. copy
makes a new instance that can be think as a "snapshot" of the data. Working on this "snapshot" guarantees that your data are not modified when you don't want them to. This effectively decouples the service and the delegate.
A side note: Your self._tweets
won't work because _tweets
is an instance variable, but the dot syntax expects a property. _tweets = [tweets copy];
would be correct.
Upvotes: 1