Objective-C should I be using NSError and why presentError function not working - objective-c

I am creating an application on iPhone where I am taking code written and Java and translating into Objective-C, as the app must work similarly in both Android and iPhone. Now problems of course are there are certain areas where the languages differ quite a bit, and can be difficult to implement just right.
One of the areas where it is of course different is you cannot create NSMutableArrays or NSMutableDictionaries which only accepts objects of a certain type. So when I am creating the getters and setters for these objects, I have been doing this, example below:
-(void)setPerson:(NSMutableArray *)personList_p
{
BOOL bAllowed = YES;
for(int i = 0; i < [personList_p count]; i++)
{
if(![[personList_p objectAtIndex:i] isKindOfClass:[Person class]])
{
bAllowed = NO;
break;
}
else
{
bAllowed = YES;
}
}
if(bAllowed)
{
personList_i = personList_p;
}
else
{
//Raise error here
}
}
Now originally I was using NSRaise Exception, but after doing reading up on it, it recommends against this as exception handling is resource intensive and should not be used for this type of situation. So NSError I read was a good solution, so I was reading up on this guide
http://www.cimgf.com/2008/04/04/cocoa-tutorial-using-nserror-to-great-effect/
My question is two fold, if I decide to use NSError should, is it best practice to declare the NSError object in the method, i.e like this
-(void)setPerson:(NSMutableArray *)personList_p : (NSError **)error
Or is it okay just to declare the error within the else statement above, like this
NSError *error = nil;
NSMutableDictionary* details = [NSMutableDictionary dictionary];
[details setValue:#"Invalid object passed into Array, object must be of type Person." forKey:NSLocalizedDescriptionKey];
error = [NSError errorWithDomain:#"Invalid Object" code:200 userInfo:details];
NSLog(#"%#", [error localizedDescription]);
Secondly, in the guide I linked above, in the conclusion the author says
In this example, I am checking to see if the error is still nil after
my message call. If it is no longer nil I know that an error occurred
and that I need to display it to the user. Apple provides a built in
method to do this with a call to presentError: on the NSApplication
instance
and he uses this line of code here
[NSApp presentError:error];
This does not work for me, I do not get an autocomplete option with this code, just says use of undeclared identifier. Am I missing something obvious here?
Also, just to be sure, is the method I am using, the best method to go about ensuring the user sends in an array with the correct object types? Or is there another method which could be used which would achieve the same thing but in a more efficient manner.
Thanks in advance!!
EDIT:
Additional question, would it be such a bad idea to use NSException, as the problem with NSError is the app carries on, I am considering having it so if they do pass in an array with an invalid object, that it does just cause the application to crash and raise an exception. Is there any major reason why I shouldn't do this??

Now originally I was using NSRaise Exception, but after doing reading
up on it, it recommends against this as exception handling is resource
intensive and should not be used for this type of situation. So
NSError I read was a good solution, so I was reading up on this guide
He does not actually say that raising exceptions is inherently bad or resource intensive, he argues that #try/catch is the wrong way to go about things. That, and Cocoa applications (even more so I'm Cocoa-Touch) should refrain from throwing exceptions whenever possible. Exceptions indicate undefined behavior, not simple errors.
Secondly, in the guide I linked above, in the conclusion the author...
uses this line of code here
[NSApp presentError:error];
This does not work for me, I do not get an autocomplete option with
this code, just says use of undeclared identifier. Am I missing
something obvious here?
That is because NSApp is a concept only accessible to Cocoa(or Mac) applications. It represents a pointer to "the application itself", and has some pretty neat functions associated with it. Of course, iOS has no parallel concept, so errors are traditionally presented in a UIAlertView.
Additional question, would it be such a bad idea to use NSException,
as the problem with NSError is the app carries on, I am considering
having it so if they do pass in an array with an invalid object, that
it does just cause the application to crash and raise an exception. Is
there any major reason why I shouldn't do this??
It is generally a bad idea to use NSException for anything other than extremely serious logic (such as when a call is made to an index out of the bounds of an NSArray, or when a UITableView's data source happens to be out of sync with what the table demands). If you absolutely must stop program execution, it's much cleaner to use NSAssert() to throw conditional exceptions. And even then, setters are not the place to be throwing exceptions. It would be far easier to simply return nil when the condition fails, then have the caller check for such an outcome and handle it appropriately.

Related

What to do if [super init] returns nil?

Take the following code as an example
- (id)init {
self = [super init];
if (self) {
// code
}
return self;
}
I do not want nil to propagate up the calling hierarchy. My initial idea is to throw an exception in case self is nil, make a restore point and abort execution.
Better ideas?
NSObject's implementation of [super init] will never return nil. The base implementation just returns self.
In general, the only reason that an initializer returns nil is if a nonfatal error occurred. For example, you might have called -initWithContentsOfURL:error: and passed an invalid URL. By convention, methods that may fail in this way have an error: parameter, which contains information about the failure. Most initializers do not have the possibility of a recoverable error, so like NSObject, they will never return nil.
Fatal errors typically throw an exception or abort the program. So checking for nil is no help with them. Your best bet to handle fatal errors is NSSetUncaughtExceptionHandler, although you should be aware that saving data is risky in the case of a fatal error, as the unsaved data may be corrupted. Don't overwrite good data in that case.
Why does objective-c code always check for nil in initializers, even when super will never return nil? Convention, mostly. Arguably, by always checking for nil, it becomes easier for a superclass to add a failure condition in the future without requiring subclasses to be changed, but really it's just a convention.
Finally, the initalizer is not the right place to check for failure in a superclass initializer. If recoverable errors are a possibility, the caller should check for the error.
Example:
NSError *error;
FooClass *myFoo = [[FooClass alloc] initWithContentsOfURL:blah error:&error]
if (myFoo == nil) {
// ...
} else {
// ...
}
Checking for nil whenever you initialize an object is overkill. This only needs to be done when there is an error: argument, or the method has a documented recoverable error.
From the docs:-
For other sorts of errors, including expected runtime errors, return
nil, NO, NULL, or some other type-‐suitable form of zero to the
caller. Examples of these errors include the inability to read or
write a file, a failure to initialize an object, the inability to
establish a network connection, or a failure to locate an object in a
collection. Use an NSError object if you feel it necessary to return
supplemental information about the error to the sender. An NSError
object encapsulates information about an error, including an error
code (which can be specific to the Mach, POSIX, or OSStatus domains)
and a dictionary of program-‐specific information. The negative value
that is directly returned (nil, NO, and so on) should be the principal
indicator of error; if you do communicate more specific error
information, return an NSError object indirectly in a parameter of the
method.
Generally speaking, just don't care and let the nil propagate.
If [super init] is returning nil (i.e. a new object could not be instantiated), something is messed up so badly that your application is likely going to crash in a matter of moments anyway.
Checking for nil after every instantiation as suggested by Michael is cumbersome and probably totally useless for the reasons above.
If there's a specific class that you are worried about, and you really want to bail out as quick as possible, go ahead as you planned and throw an exception.
About "making a restore point" you can try to save whatever possible, but the scenario is so compromised that there's no guarantee of succeeding.
I suppose "[super init]" could throw nil if you're trying to reserve a 20 gig block of memory or something (which nobody doing iOS coding would ever do), but in general, a "nil" being returned rarely happens in production code.
The nice thing about "nil" being returned is that you can send messages to a nil object and your application won't crash.
But you should always do checks for nil after instantiating an object, just to make sure you don't get too deep into something your app (or your user) can't recover from.
In Apple's "Concepts in Objective C" document, they suggest "When you create an object, you should generally check whether the returned value is nil before proceeding:".

NSKeyedUnarchiver - try/catch needed?

As I understand, the use of #try/#catch blocks is discouraged, because exceptions should only be thrown at unrecoverable, catastrophic errors (refer to this discussion with a nice answer by #bbum: Exception Handeling in iOS).
So I looked through my code and found a #try/#catch block that I don't know how to get rid of:
NSData *fileData = [NSData dataWithContentsOfFile: ....];
NSDictionary *dictionary;
#try {
dictionary = [NSKeyedUnarchiver unarchiveObjectWithData: fileData];
}
#catch (NSException *exception) {
//....
}
#finally {
//...
}
The problem is that (as stated in the documentation) +unarchiveObjectWithData: raises an NSInvalidArchiveOperationException if the NSData doesn't contain a valid archive.
Since the data is provided by a file the user chose, it is not guaranteed that it contains a valid archive, and thus the application would crash if a incorrect file was chosen.
Now two questions:
Why doesnt +unarchiveObjectWithData: just return nil (Edit: and an NSError**) if the archive is not valid (this doesn't seem to qualify as a catastrophic or unrecoverable error).
Is the pattern above correct (using #try)? I have found no method that lets us check if the data contains a valid archive beforehand and have found no possibility to handle this case using the delegate protocol. Antyhing I overlooked?
Note that the code above of course works, I just wonder if its the best practice.
There was a new method added in iOS 9 to NSKeyedUnarchiver that now returns an error:
Swift:
public class func unarchiveTopLevelObjectWithData(data: NSData) throws -> AnyObject?
Objective-C:
+ (nullable id)unarchiveTopLevelObjectWithData:(NSData *)data error:(NSError **)error;
However, this is not backwards compatible with previous versions of iOS, so you will need to check for framework availability.
NSKeyedArchiver is built by Apple. They control the code that is performed while unarchiveObjectWithData: executes so they also control resource management during exception handling (which is the source of trouble behind exceptions in Objective-C).
If they can guarantee that in between your call to unarchiveObjectWithData: and the point in code where they raise the exception is no foreign code (neither third party nor your app's code) it is in theory possible to safely use an exception, as long as calling code takes care of cleaning up correctly.
The problem is that this assumption might not be the case: It is common to use NSKeyedArchiver to serialize custom objects. Usually the custom class implements initWithCoder: to read the classes data (by using the archiver's methods like decodeObjectForKey:).
If the archiver throws an exception in one of these methods there's no way to fix resource handling for the archiver. The exception will be thrown through the custom object's initWithCoder:. The archiver does not know if there's more stuff to clean up than the deserialized objects. So in this scenario the occurrence of the exception means that the process is in a dangerous state and unwanted behavior may result.
Regarding your questions:
Why doesn't [NSKeyedArchiver use proper Cocoa error handling]?
Only the Apple engineers who built the archiver know. My guess is that exception handling and keyed archiving were built at roughly the same time (around 2001) and at that point it wasn't yet clear that exception handling would never be a first class citizen in Objective-C.
Is the #try pattern correct?
With the limitation of the caveats described above it is correct. If Apple's code handles the exception cases properly and your own serialization code does the same the #try pattern might be correct.
It is very difficult to achieve full correctness, though. You'd have to make sure all executed code is aware of the exceptions and does cleanup correctly.
ARC, for instance, does no exception cleanup for local variables and temporary objects by default (you would have to enable -fobjc-arc-exceptions to do this).
Also, there's no documentation on exception safety of the accessors of #synthesized properties (when atomic they might leak a lock).
Conclusion:
There are a myriad of subtle ways of how exceptions can break stuff. It is difficult and requires in depth knowledge of the implementation of all involved parts to build exception safe code in Objective-C.
All this leads to the conclusion. If you want to handle errors gracefully while loading possibly corrupted archives and continue normal execution afterwards: Do not use NSKeyedArchiver.

NSError objects with NSFetchedResultsControllers

This is a simple one: I'm currently creating a new NSError object every time I perform a fetch on my NSFetchedResultsController. This occurs across a number of methods, so there are currently nine of them in my main view controller. Should I create one NSError as a property and use that, or is it more conventionally accepted to create a new one each time you use it?
I'm guessing the advantage of creating multiples is that if more than one error occurs, you can get at both independently, but if this is unlikely to occur, is it acceptable to use a shared one for all performFetch calls? I'm learning a lot of programming convention and technique, so apologies if this is something of a non-issue, I'd just like to get some feedback on the more typical approach to using NSError objects in a variety of places.
You aren't really creating NSError objects. You are declaring references to NSError objects and then passing the reference to a method which may point the reference at an NSError object it creates.
NSError *err; // just a reference, no object created
// this creates an object, but you don't do this
err = [NSError errorWithDomain:#"foo" code:0 userInfo:nil];
// You do this....
BOOL success = [fetchedResultsController performFetch:&err];
The distinction is, you aren't really creating a bunch of objects which require overhead. So if you re-use the same variable for all of them or you create a new variable for each one, it isn't going to impact performance.
So to answer the question... either use 1 variable or many as you see fit. Some code might fail on any error and refuse to continue so 1 error is fine. Other code might want to try and keep going so you keep all the errors and spew them out at the end. It's a matter of what fits best with the specific coding you are working on at the time.
Just declaring one on the stack and passing it's address is virtually free. So you could do:
NSError *errorA;
// do something, passing &errorA
if (!errorA) {
// do something passing &errorA again
}
Or, at hardly any additional cost (just another pointer on the stack)
NSError *errorA, *errorB;
// do something, passing &errorA
// do something, passing &errorB, that doesn't care whether the last thing succeeded
if (!errorA && !errorB) {
// do something else
}
There's no need to worry about allocations of NSError here. It should be more about the logic of dependency between the first action success and doing a second action.

how to use pointers in Objective c

I have seen some iOS developpers using code like this :
- (void)setupWebView:(UIWebView**)aWebView {
UIWebView *webview = [[UIWebView alloc] init];
.....
if (*aWebView) {
[*aWebView release];
}
*aWebView = webview;
}
Do you know what'is this mean and why we use this ? thanks
- (void)setupWebView:(UIWebView**)aWebView {
That is awful. You should never have a method that returns void, but sets an argument by reference unless:
• there are multiple arguments set
• the method is prefixed with get
That method should simply return the created instance directly. And this just makes it worse -- is flat out wrong:
if (*aWebView) {
[*aWebView release];
}
*aWebView = webview;
it breaks encapsulation; what if the caller passed a reference to an iVar slot. Now you have the callee managing the callers memory which is both horrible practice and quite likely crashy (in the face of concurrency, for example).
it'll crash if aWebView is NULL; crash on the assignment, specifically.
if aWebView refers to an iVar slot, it bypasses any possible property use (a different way of breaking encapsulation).
It is a method to initialize a pointer. The first line allocates the object. The if statement makes sure that the passed in pointer-to-a-pointer is not already allocated, if it is it releases it. then it sets the referenced pointer to the newly allocated object.
The answer by #bbum is probably correct, but leaves out one aspect to the question that I see there. There are many examples in Foundation which use pointer-pointers in the method signature, so you can say it is a common pattern. And those are probably not a beginners mistake.
Most of these examples are similar in that they fall into one category: the API tries to avoid the usages of exceptions, and instead use NSError for failures. But because the return value is used for a BOOL that signals success, an NSError pointer-pointer is used as output parameter. Only in the probably rare error case an NSError object is created, which can contain error code and error descriptions, and localized descriptions and possibly even more information (like an array of multiple errors in the case of bulk operations). So the main success case is efficient, and the error case has some power to communicate what went wrong, without resorting to exceptions. That is the justification behind these signatures as I understand it.
You can find examples of this usage in both NSFileManager and NSManagedObjectContext.
One might be tempted to use pointer-pointers in other cases where you want multiple return values and an array does not make sense (e.g. because the values are not of same type), but as #bbum said, it is likely better to look hard for alternatives.

Using Exception Handling versus NSError in Cocoa Apps

Hey all. I've been reading up on Apple's suggestions for when/where/how to use NSError versus #try/#catch/#finally. Essentially, my impression is that Apple thinks it best to avoid the use of exception handling language constructs except as a mechanism for halting program execution in unexpected error situations (maybe someone could give an example of such a situation?)
I come from Java, where exceptions are the way to go when one wants to handle errors. Admittedly, I'm still in the Java thoughtspace, but I'm slowly coming to grips with all that NSError has to offer.
One thing I'm hung up on is the task of cleaning up memory when an error occurs. In many situations (e.g. using C, C++ libraries, CoreFoundation, etc..) you have a lot of memory cleanup that needs to be done before breaking out of a function due to an error.
Here's an example I cooked up that accurately reflects the situations I've been encountering. Using some imaginary data structures, the function opens up a file handle and creates a 'MyFileRefInfo' object which contains information about what to do with the file. Some stuff is done with the file before the file handle is closed and the memory for the struct freed. Using Apple's suggestions I have this method:
- (BOOL)doSomeThingsWithFile:(NSURL *)filePath error:(NSError **)error
{
MyFileReference inFile; // Lets say this is a CF struct that opens a file reference
MyFileRefInfo *fileInfo = new MyFileRefInfo(...some init parameters...);
OSStatus err = OpenFileReference((CFURLRef)filePath ,&inFile);
if(err != NoErr)
{
*error = [NSError errorWithDomain:#"myDomain" code:99 userInfo:nil];
delete fileInfo;
return NO;
}
err = DoSomeStuffWithTheFileAndInfo(inFile,fileInfo);
if(err != NoErr)
{
*error = [NSError errorWithDomain:#"myDomain" code:100 userInfo:nil];
CloseFileHandle(inFile); // if we don't do this bad things happen
delete fileInfo;
return NO;
}
err = DoSomeOtherStuffWithTheFile(inFile,fileInfo);
if(err != NoErr)
{
*error = [NSError errorWithDomain:#"myDomain" code:101 userInfo:nil];
CloseFileHandle(inFile); // if we don't do this bad things happen
delete fileInfo;
return NO;
}
CloseFileHandle(inFile);
delete fileInfo;
return YES;
}
Now.. my Java logic tells me that it would be better to set this up as a try/catch/finally structure and put all the calls to close the file handle and free memory in the finally block.
Like so..
...
#try
{
OSStatus err = OpenFileReference((CFURLRef)filePath ,&inFile);
if(err != NoErr)
{
... throw some exception complete with error code and description ...
}
err = DoSomeStuffWithTheFileAndInfo(inFile,fileInfo);
if(err != NoErr)
{
... throw some exception ...
}
... etc ...
}
#catch(MyException *ex)
{
*error = [NSError errorWithDomain:#"myDomain" code:[ex errorCode] userInfo:nil];
return NO;
}
#finally
{
CloseFileHandle(inFile); // if we don't do this bad things happen
delete fileInfo;
}
return YES;
Am I crazy in thinking that this is a much more elegant solution with less redundant code?
Did I miss something?
Daniel's answer is correct, but this question deserves a rather more blunt answer.
Throw an exception only when a non-recoverable error is encountered.
Use NSError when communicating error conditions that may be recovered from.
Any exception that is thrown through a frame in Apple's frameworks may result in undefined behavior.
There is an Exceptions programming topic document available in the dev center.
Essentially, my impression is that Apple thinks it best to avoid the use of exception handling language constructs except as a mechanism for halting program execution in unexpected error situations (maybe someone could give an example of such a situation?)
That's not quite my impression. I thought that Apple suggests using exceptions for truly exceptional conditions, and NSError for expected failures. Since you come from Java, I think NSError -> java.lang.Exception, and Obj-C Exceptions -> java.lang.RuntimeException. Use an Obj-C exception when the programmer did something wrong (used an API incorrectly, for example), and use NSError when an expected failure occurred (the remote server could not be found, for example).
Of course, that's just my interpretation of Apple's position. I, on the other hand, like exceptions!
Exceptions in Objective-C have historically been 'heavy', with a performance cost to entering a try block, a cost to throwing, a cost to using finally, etc. As a result Cocoa developers have typically avoided exceptions outside of 'oh no, the sky is falling' sorts of situations -- if a file is missing, use an NSError, but if there's no filesystem and a negative amount of free memory, that's an exception.
That's the historical view. But if you're building a 64-bit app on 10.5 or newer, the exception architecture has been rewritten to be 'zero cost', which may mean that the historical view is no longer relevant. As with just about anything, it comes down to various factors -- if working one way is more natural to you and will let you finish more quickly, and if you don't experience any performance-related problems with it, and if being slightly inconsistent with 'traditional' Objective-C code doesn't bother you... then there's no reason not to use exceptions.
According to More iPhone 3 Development by Dave Mark and Jeff LeMarche, exceptions in are used only for truly exceptional situations and usually indicate a problem within your code. You should never use exceptions to report a run-of-the-mill error condition. Exceptions are used with much less frequency in Objective-C than in many other languages, such as Java and C++.
You use an exception when you need to catch a mistake in your code. You use an error when the user may need to fix the problem.
Here's an example where you would use an exception:
We're writing a superclass, and we want to make sure its subclasses implement a given method. Objective-C doesn't have abstract classes, and it lacks a mechanism to force a subclass to implement a given method. Yet we can use an exception to instantly inform us that we forgot to implement the method in a subclass. Instead of an unpredictable behavior, we'll get slammed with a runtime exception. We can easily debug it because our exception will tell us exactly what we did wrong:
NSException *ex = [NSException exceptionWithName:#"Abstract Method Not Overridden" reason:NSLocalizedString(#"You MUST override the save method", #"You MUST override the save method") userInfo:nil];
[ex raise];
Because problem is a programmer mistake rather than a problem the user may be able to fix, we use an exception.