Accessors / Getters and Lazy Initialization - iphone

I have a question about overriding auto-generated accessor methods. The following would not work (I believe) because each getter references the other getter. Is there a rule that accessor methods should not use other accessor methods, or do you just have to watch out for these situations individually?
-(UIImage *) image{
if(image == nil){
if(self.data == nil){
[self performSelectorInBackground: #selector(loadImage) withObject: nil]
}else{
self.image = [UIImage imageWithData: self.data];
}
}
return image;
}
-(NSData *) data {
if(data == nil){
if(self.image == nil){
[self performSelectorInBackground: #selector(loadData) withObject: nil]
}else{
self.data = UIImageJPEGRepresentation(self.image, 0.85);
}
}
return data;
}
I have to emphasize that the image use presented here is an example, and thoughts concerning what to do in this particular example are less important than in the general case.

First, don’t be too smart for your own good. If you want to get over some bottleneck, first measure and make sure it’s really there. I believe that both UIImage and NSData do some internal lazy loading, so that your code might be essentially useless. Second, even if you really wanted to do something like that by hand, try splitting the caching code into a separate class, so that you don’t pollute the code of the main class.
There is no rule about accessors (at least no that I know of), because people don’t do much lazy loading in accessors. Sometimes I get myself caught by an endless loop caused by lazy [UIViewController loadView] in combination with [UIViewController view], but that’s about it.

There's nothing that forbids it, but you're definitely writing some confusing code. Essentially, these two properties have a circular dependency. This is hard to both read and debug. It's not clear why you'd want to "load the data" before you "load the image", or why you'd also want to support "loading the image" before you "load the data", or really how the two properties are really two different things.

what you're actually doing in this example could take a long time to load; it is best to ensure that it is thread safe.
furthermore, it would be even better if you made the data object a real data provider (typically using protocols), separate from the class, and to make the image container expose that it is handling a lazily loaded object (which may cause outcry from some people).
specifically, you may want to invoke a load data/image from the provider, call it from awakeFromNib (for example) - then the loader runs off and loads the data on a secondary thread (esp. if downloaded). give the data provider a callback to inform the view that the image is ready (typically using protocols). once the view takes the unarchived image, invalidate the data provider.
finally, if you're dealing with app resources, the 'system' will cache some of this for you sooo you'd be attempting to work against what's already optimised behind the scenes.
in short, it's usually ok (e.g. not lazy initialization) - but this specific design (as another poster said) has a circular dependency which should be minimized.

Related

Core Data merge behaviour

I tried to find an answer to this question, but I couldn't figure out a question from neither the doc nor StackOverflow. If there is already a question like this, I just didn't find it, so it will be very welcomed as the solution in case.
My situation is:
I have two core data entities, a User and a Driving Licence.
User <--- 1 to 1 ---> Driving Licence
I'm using Magical Record as an abstraction layer for the core data operations.
My User class (derived from NSManagedObject) exposes 2 methods.
One to access a singleton instance of the User (the only one used throughout the app):
+ (User *)currentUser {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if ([User MR_findFirst] == nil) {
User *user = [User MR_createEntity];
user.drivingLicence = [DrivingLicence MR_createEntity];
[[user managedObjectContext] MR_save];
}
});
return [User MR_findFirst];
}
And a method used to reset the user data (derived from NSManagedObject):
- (void)resetFields
{
self.name = nil;
self.surname = nil;
....
[self.drivingLicence MR_deleteEntity];
self.drivingLicence = [DrivingLicence MR_createEntity];
[self.managedObjectContext MR_save];
}
Sometimes, I would say quite randomly, the drivingLicence field happens to be null.
There may be occasions when the resetFields method is called by a background thread.
Could it be that, for the merge with the other contexts, tha sequence of instructions
[self.drivingLicence MR_deleteEntity];
self.drivingLicence = [DrivingLicence MR_createEntity];
can cause some confusion, bringing the drivingLicence to be just deleted at end?
Or what else could it be the reason for this unexpected null value?
When you use MR_createEntity, you are implicitly using the default context, accessed through [NSManagedObjectContext MR_defaultContext]. It is quite dangerous to do this unless you are ABSOLUTELY POSITIVE you are calling that from the main thread. In your examples, all this should work correctly if everything is called from the main thread AND your self.managedObjectContext instance variable is also pointing to the default context. Otherwise, you will need to be explicit about which contexts you are using. MagicalRecord provides these conventions for you by having an inContext: optional parameter at the end of every method that requires a context to work. Have a look at the MR_createInContext: method and be explicit with your context usage
Just hit this problem. Based on our discoveries, I wanted to add some comments to casademora's answer above:
It is important to remember that core data, as well as any of the MR_save methods, are not thread safe. We delegate our MagicalRecord actions to a queue to get around this issue. Specifically, it's important to remember not to do save actions (such as MR_saveToPersistentStoreAndWait) in multiple threads at the same time.
However the connection between MR_createEntity, MR_defaultContext, and the Main thread is more subtle. As of MagicalRecord version 2.3.x, I do not believe that MR_createEntity, with no arguments, defaults to MR_defaultContext. I believe it defaults to the MR_contextForCurrentThread. MR_contextForCurrentThread returns the default context if it's on the Main thread, but otherwise it does not. This is dangerous if you don't understand the consequences, as you could easily see what the original poster sees above (lost data).
In fact, this note indicates that you should use MR_createEntityInContext:localContext rather than MR_createEntity due to problems with MR_contextForCurrentThread when using GCD.
See the function definition in github for the logic where MR_createEntity uses MR_contextForCurrentThread.

Memory about lazy loading

I am reading tutorial book now. When I see an example, I get some confused.
The following codes show a way for lazy loading. Does this motivations array be released after instance deallocated ? or will it occupy this memory block until application terminates.
+ (NSArray *)motivations
{
static NSArray *motivations = nil;
if (!motivations)
{
motivations = [[NSArray alloc] initWithObjects:#"Greed",#"Revenge",#"Bloodlust",#"Nihilism",#"Insanity",nil];
}
return motivations;
}
Edit 1
Thank Georg for a bug.
The example you show has a bug - +arrayWithObjects: returns an autoreleased instance which will be destroyed later. The code was probably intended to be:
motivations = [[NSArray alloc] initWithObjects:#"Greed",#"Revenge",#"Bloodlust",#"Nihilism",#"Insanity",nil];
With that, the array will live until the application terminates.
Because it is a static object, so the system will store the object pointer until the application is terminated. You can use this way to cache by let your pointer point to an object that is not release or autorelease
I recommend to use this approach when you really want to cache some data in memory (usually small or big images data) that requires a lot of CPU or IO processing time to generate. For small data like NSString, you can create new array and return every time you need.
Edit for the comment:
There are 2 things about imageNamed:
1/ You cannot control what is cached and what is not cached by imageNamed:. You may not want to cache an image with big size and only used once, for example.
2/ imageNamed: cannot be used for getting image from Network or folders in the system. It will only load from your bundle
Since this is a class method (indicated by a + instead of a - at the declaration), there is no instance that will be released. (Technically there is an instance of an object of class isa I think (? comment if I'm wrong please, I don't know the inner workings very well) but don't worry about that)
So the class, which exists in memory the whole time the program is running, owns that array. Think of static as about as close as you can get to a class variable, rather than an instance variable. Since the class exists the whole time, the array exists the whole time.
Lazy loading keeps it from being created until the first time that class method is called though, so it isn't wasting memory until you need it.

Memory leak using (void) alloc

I have seen a similar line of code floating about in Apples code:
(void)[[URLRequest alloc] initializeRequestWithValues:postBody url:verifySession httpHeader:nil delegate:self];
URLRequest is my own custom class. I didn't write this and I think the guy that did just grabbed it from Apple's example. To me this should leak and when I test it I'm pretty sure it leaks 16 bytes. Would it? I know how to fix it if it does but wasn't sure as it was taken from Apple's code.
EDIT: The problem was with the SDK, not the above code. See answer below for further details
Thought I might update this as after further testing and the release of iOS4 it has changed.
The above code doesn't leak and the memory footprint of the App returns to normal even after 200 iterations of the code. The leak did occur in iOS3 but was very small, in iOS4 it has completely disappeared both in simulator and device.
Some might wonder why you would want to implement this code but it works and make sense when dealing with lots of different NSURLConnections throughout your code running simultaneously.
Yes. This is a leak, which can easily be fixed by adding an autorelease:
[[[URLRequest alloc] initializeRequestWithValues:postBody url:verifySession httpHeader:nil delegate:self] autorelease];
Perhaps a better fix would be to create a class function that does this:
#interface URLRequest
{
// ...
}
// ...
+ (void) requestWithValues:/* ... */
// ...
#end
Then you could simply use [URLRequest requestWithValues: /* ... */] without invoking alloc.
Not at all sure what this code is supposed to accomplish. It does appear to break every single convention about initialization methods. What's the point of returning a void pointer from an initialization method? The entire point of an initialization method is to return an object. Where in Apple's code examples did you see this?
Having said that, I don't see why it would leak. Since it doesn't return an object there is nothing to leak external to the method. There might be something internally that leaks.
Edit:
It basically does an NSURLConnection.
Because we are submitting a lot of
forms with a lot of different values
we put it in an external class. All
the delegate methods like
didFailWithError: are in NSURLRequest
and connectionDidFinishLoading just
passes the data to its delegate. So it
doesn't really need to return anything
as it is done through a delegate
method.
Yeah, you need to redesign this. At present, this method is just a disaster waiting to happening. If nothing else, everyone else looking at this code will be utterly confused about what you are doing.
If you have no need to retain the object created, then move its allocation and clean up entirely within a method. Change the method name prefix from "initialize" to something like "setup", "configure", "acquire" etc so the name doesn't imply that it creates and returns and object.
If you need a one shot instance of a particular class, use a class method like Michael Aaron Safyan suggested (again without initialize in the name.) The class method should internally initialize an instance, perform the operations needed, return the data to wherever, then dealloc the instance.
That way, you won't have to worry about leaks and everyone else who may read your code (including yourself months down the road) will immediately understand what the code does.

How to copy objects, like AVAudioPlayer

I'm rather surprised at how few objects implement NSCopying. This is the third time in two weeks where I have needed to duplicate an existing object, without having to either go to disk and reload, or recreate the object and set its settings.
Now I have to duplicate an AVAudioPlayer sound. Why? I want to play the sound twice, without having the sound.currentTime determine the playback location of the second playback.
I thought it might be easy to do a category or subclass AVAudioPlayer and implement copyWithZone. However, the internals of AVAudioPlayer are hidden and I can't easily copy them.
I am now yearning for the good old BlockMove(&var, &newVar, sizeof(varType));
How best to duplicate an AVAudioPlayer sound or a UIView view?
The reason why many objects don't support NSCopying is because it's not always clear on what a copied object should be, and in particular, the excessively pedantic details of what it means to 'copy an object'.
I would take a pragmatic approach in this case. If you need an instance of AVAudioPlayer duplicated just once, I'd recommend this:
AVAudioPlayer *audioPlayer; // Assumed to be valid.
AVAudioPlayer *copiedPlayer = NULL;
copiedPlayer = [[[AVAudioPlayer allocate] initWithData:audioPlayer.data] autorelease];
This is not meant to be a general solution because it does not handle all cases. It's meant to be an example of how you can over come the problem while relying on some usage specific invariants. The most notable example in which this breaks is if audioPlayer was not initialized with a NSData object, but a url instead. It also makes certain relatively safe assumptions about the mutability of data, and how AVAudioPlayer was coded to handle those cases. (I did not look at the documentation long enough to see if such corner case behaviors are documented).
If this is something you need to do a lot, you can probably lash together a more complicated bit of code that implements NSCopying. Since a quick pass at the documentation turns up only two ways to init the object, via a NSData or via a url, and the instantiated object to be copied provides that information... then the implementation of a non-optimal deep copy NSCopying subclass is left as an exercise for the reader. :)
I saw an Apple sample file, CASound.mm, which has a -copyWithZone:
/* support NSCopying */
- (id)copyWithZone:(NSZone *)zone
{
CASound* copy = NSCopyObject(self, 0, zone);
copy->_impl = NULL;
[copy initWithSound: self];
return copy;
}
looking at initWithSound:
- (CASound*)initWithSound:(CASound *)other
{
CASoundImpl* otherImpl = (CASoundImpl*)other->_impl;
if (otherImpl->_url) {
return [self initWithContentsOfURL: otherImpl->_url];
} else if (otherImpl->_data) {
return [self initWithData: otherImpl->_data];
} else {
return NULL;
}
}
Now, I don't know if Apple likes us messing around with the private fields like _impl, but this basically boils down to the same thing as getting the AVPlayer all over again from the file, and not just making an in-memory copy of the existing sound.
I was actually hoping that maybe NSCopyObject would do the deed, but I see Apple doesn't rely on it for the entire copy.

Dealing with variable assignments and async requests

I'm looking for a reliable design for handling assignments that have asynchronous requests involved. To further clarify, I have a class which handles Data Management. It is a singleton and contains a lot of top level data for me which is used throughout my iPhone application.
A view controller might do something such as the following:
users = [MySingleton sharedInstance].users;
MySingleton will then override the synthesized users getter and see if it is set. If it is not set, it will speak to a Connection Manager (a wrapper for NSURLConnection and its delegate methods) which fires off an asynchronous request, and this is where problems begin. I cannot guarantee when "users" will be available. I could change the request to synchronous, but that will directly effect user experience, especially in a mobile environment where bandwidth is limited already.
I need to be able to at some point, have some kind of locking/synchronization code going on in my getter that doesn't return users until it is available or is nil.
Once the NSURLConnection has the data available, it needs to callback something/somewhere with a response object and let the getter know the data is available.. whether it's failed or succeeded.
Any suggestions on handling this?
I solved this problem a couple ways in different apps.
One solution is to pass an object and selector along to notify such as:
- (id)getUsersAndNotifyObject:(id)object selector:(SEL)selector
This breaks the nice property behavior however. If you want to keep the methods as properties, have them return immediately, with either cached data or nil. If you need to go out to the network, do so asynchronous and then let the rest of the app know the data changed via KVO or the NSNotificationCenter. (Cocoa Bindings would be an option on the Mac, but they don't exist on iPhone).
The two methods are fairly similar. Register for updates with your shared instance, and then ask for the data. KVO is a little lighter weight if you just dealing with raw observable properties, but an NSNotification might be more convenient if you're interested in several different pieces of data.
With an NSNotification, the client object could register for one type of notification which includes the changed data in its userInfo dictionary instead of having to register obvservers for every single key path you're interested in.
An NSNotification would also allow you to pass back failures or other status information a lot more easily than straight KVO.
KVO method:
// register observer first so you don't miss an update
[[MySingleton sharedInstance] addObserver:self
forKeyPath:#"users"
options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
context:&kvo_users_context];
users = [MySingleton sharedInstance].users;
// implement appropriate observeValueForKeyPath:ofObject:change:context: method
NSNotification Method:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(sharedDataChanged:)
name:MySingletonDataUpdatedNotification
object:[MySingletonDataUpdatedNotification sharedInstance]];
users = [MySingleton sharedInstance].users;
// implement appropriate sharedDataChanged: method
You can either use a delegate pattern or a notification pattern here.
A delegate would let a particular object know when users is complete, a notification pattern would notify any object that wants to know. Both are valid, depending on your situation.
Just remember: if you have any race issues in your app, your architecture is probably all wrong.
It took me a while to realize what the best way of handling this kind of typical task; it turns out the clue is in the design of many of Cocoa and CocoaTouch's own APIs: delegation.
The reason so many of Cocoa's APIs use delegation is because it fits very well with the asynchronous nature of many GUI apps.
It seems perfectly normal to want do do something along the lines of:
users = [MyDataFactory getUsers];
Except, as you point out, you have no idea when the getUsers method will finish. Now, there are some light-weight solutions to this; amrox mentioned a few in his post above (personally I'd say notifications aren't such a good fit but the object:selector: pattern is reasonable), but if you are doing this kind of thing a lot the delegation pattern tends to yield a more elegant solution.
I'll try to explain by way of an example of how I do things in my application.
Let's say we have a domain class, Recipe. Recipes are fetched from a web service. I typically have a series of repository classes, one for each entity in my model. A repository class' responsibility is to fetch the data required for the entity (or a collection of them), use that data to construct the objects, and then pass those objects onto something else to make use of them (typically a controller or data source).
My RecipeRepository interface might look something like this:
#interface RecipeRepository {}
- (void)initWithDelegate:(id)aDelegate;
- (void)findAllRecipes;
- (void)findRecipeById:(NSUInteger)anId;
#end
I'd then define a protocol for my delegate; now, this can be done as an informal or formal protocol, there are pros and cons of each approach that aren't relevant to this answer. I'll go with a formal approach:
#protocol RepositoryDelegateProtocol
- (void)repository:(id)repository didRetrieveEntityCollection:(NSArray *)collection;
- (void)repository:(id)repository didRetrieveEntity:(id)entity;
#end
You'll notice I've gone for a generic approach; you will likely have multiple XXXRepository classes in your app and each will use the same protocol (you may also choose to extract a base EntityRepository class that encapsulates some common logic).
Now, to use this in a controller, for example, where you previous would have done something such as:
- (void)viewDidLoad
{
self.users = [MySingleton getUsers];
[self.view setNeedsDisplay];
}
You would do something like this:
- (void)viewDidLoad
{
if(self.repository == nil) { // just some simple lazy loading, we only need one repository instance
self.repository = [[[RecipeRepository alloc] initWithDelegate:self] autorelease];
}
[self.repository findAllRecipes];
}
- (void)repository:(id)repository didRetrieveEntityCollection:(NSArray *)collection;
{
self.users = collection;
[self.view setNeedsDisplay];
}
You could even extend this further to display some kind of "loading" notice with an additional delegate method:
#protocol RepositoryDelegateProtocol
- (void)repositoryWillLoadEntities:(id)repository;
#end
// in your controller
- (void)repositoryWillLoadEntities:(id)repository;
{
[self showLoadingView]; // etc.
}
Another thing about this design is that your repository classes really don't need to be singletons - they can be instantiated wherever you need them. They may deal with some kind of singleton connection manager but at this layer of abstraction a singleton is unnecessary (and its always good to avoid singletons where possible).
There is a downside to this approach; you may find you need layers of delegation at each level. For instance, your repositories may interact with some kind of connection object which does the actual asynchronous data loading; the repository might interact with the connection object using it's own delegation protocol.
As a result you might find you have to "bubble up" these delegation events throughout the different layers of your application using delegates that get more and more coarse-grained as they get closer to your application-level code. This can create a layer of indirection that can make your code harder to follow.
Anyway, this is my first answer on SO, I hope its been helpful.