Related
This might be a silly question, but I just wanted to know. I want my code to detect if ARC is enabled, programmatically. How do I do that? Is there is any flag that I could check? Actually the problem is that, I have written an open-source library. I have used release and retain in it. if some one else uses my library files using ARC enabled, I dont want them to get any errors. how do I achieve this? or is there any possible ways I can provide any tools to compile my library before using it?
#if !__has_feature(objc_arc)
//Do manual memory management...
#else
//Usually do nothing...
#endif
This is of course a compile-time check, you cannot check for ARC at runtime.
An alternative would be to set the -fno-objc-arc compiler flag for your files that use manual memory management in a project that otherwise uses ARC.
Whether you want to bother with this at all or just use ARC everywhere depends on how backward-compatible you want/need to be. Code that supports both ARC and MRC can get quite hard to read and maintain.
You don't detect it programmatically, it operates based on translations. That is, it is not like Garbage Collection -- which is process-wide, required all linked libraries to support (and implement it correctly in that mode). You can have some files compiled with ARC, and some without.
However, you can detect it at compilation.
As far as the distribution of your library: I would not bother with a translation based system, where ref count ops are conditionally enabled. I would (personally) just support one model (MRC in your case, until you choose to migrate it to ARC), then expect people to link to the library, or if they compile it in a target they configure, to disable ARC. Conditionally enabling/disabling code based on the presence of a feature is asking for tough bugs, particularly when it's likely to affect 9% of your library's lines of code.
NO, you can't, Xcode would not compile in ARC projects if your source uses retain-release
Maybe it's useful if calling a method that MyClass doesn't understand on a something typed MyClass is an error rather than a warning since it's probably either a mistake or going to cause mistakes in the future...
However, why is this error specific to ARC? ARC decides what it needs to retain/release/autorelease based on the cocoa memory management conventions, which would suggest that knowing the selector's name is enough. So it makes sense that there are problems with passing a SEL variable to performSelector:, as it's not known at compile-time whether the selector is an init/copy/new method or not. But why does seeing this in a class interface or not make any difference?
Am I missing something about how ARC works, or are the clang warnings just being a bit inconsistent?
ARC decides what it needs to retain/release/autorelease based on the cocoa memory management conventions, which would suggest that knowing the selector's name is enough.
This is just one way that ARC determines memory management. ARC can also determine memory management via attributes. For example, you can declare any typedef retainable using __attribute__((NSObject)) (never, ever do this, but it's legal). You can also use other attributes like __attribute((ns_returns_retained)) and several others to override naming conventions (these are things you might reasonably do if you couldn't fix the naming; but it's much better to fix the naming).
Now, imagine a case where you failed to include the header file that declares these attributes in some files but not others. Now, some compile units (.m files) memory manage it one way and some memory manage it another. Hijinks ensure. This is much, much worse than the situation without ARC, and the resulting bugs would be mindbending because some ARC code would do one thing and other ARC code would do something different.
So, yeah, don't do that. (Of course you should never ignore warnings in Objective-C anyway, but this is a particularly nasty situation.)
It's an ounce of prevention, I'd assume. Incidentally, it's not foolproof in larger systems because selectors do not need to match and matching is all based on the translation, so it could still blow up on you if you are not writing your program such that it introduces type safety. Something is better than nothing, though!
The compiler wants to know about parameters and return types, potentially annotations and out parameters. ObjC has defaults to fall back on, but it's a good source of multiple types of bugs as the compiler does more for you.
There are a number of reasons you should introduce type safety and turn up the warning levels. With ARC, there are even more. Regardless of whether it is truly necessary, it's a good direction for an objc compiler to move towards (IMHO). You might consider C99 safer than ObjC 2.0 in this regard ;)
If there really is a restriction for codegen, I'd like to hear it.
I have recently read Apple's sample code for MVCNetworking written by Apple's Developer Technical Support guru Quinn "The Eskimo!". The sample is really nice learning experience with what I guess are best development practices for iOS development.
What surprised me, coming from JVM languages, are extremely frequent assertions like this:
syncDate = [NSDate date];
assert(syncDate != nil);
and this:
photosToRemove = [NSMutableSet setWithArray:knownPhotos];
assert(photosToRemove != nil);
and this:
photoIDToKnownPhotos = [NSMutableDictionary dictionary];
assert(photoIDToKnownPhotos != nil);
Is that really necessary? Is that coding style worth emulating?
If you're used to Java, this may seem strange. You'd expect an object creation message to throw an exception when it fails, rather than return nil. However, while Objective-C on Mac OS X has support for exception handling; it's an optional feature that can be turned on/off with a compiler flag. The standard libraries are written so they can be used without exception handling turned on: hence messages often return nil to indicate errors, and sometimes require you to also pass a pointer to an NSError* variable. (This is for Mac development, I'm not sure whether you can even turn exception handling support on for iOS, considering you also can't turn on garbage collection for iOS.)
The section "Handling Initialization Failure" in the document "The Objective-C Programming Language" explains how Objective-C programmers are expected to deal with errors in object initialization/creation: that is, return nil.
Something like [NSData dataWithContentsOfFile: path] may definitely return nil: the documentation for the method explicitly says so. But I'm honestly not sure whether something like [NSMutableArray arrayWithCapacity: n] ever returns nil. The only situation I can think of when it might is when the application is out of memory. But in that case I'd expect the application to be aborted by the attempt to allocate more memory. I have not checked this though, and it may very well be that it returns nil in this case. While in Objective-C you can often safely send messages to nil, this could then still lead to undesirable results. For example, your application may try to make an NSMutableArray, get nil instead, and then happily continue sending addObject: to nil and write out an empty file to disk rather than one with elements of the array as intended. So in some cases it's better to check explicitly whether the result of a message was nil. Whether doing it at every object creation is necessary, like the programmer you're quoting is doing, I'm not sure. Better safe than sorry perhaps?
Edit: I'd like to add that while checking that object creation succeeded can sometimes be a good idea, asserting it may not be the best idea. You'd want this to be also checked in the release version of your application, not just in the debug version. Otherwise it kind of defeats the point of checking it, since you don't want the application end user to, for example, wind up with empty files because [NSMutableArray arrayWithCapacity: n] returned nil and the application continued sending messages to the nil return value. Assertions (with assert or NSAssert) can be removed from the release version with compiler flags; Xcode doesn't seem to include these flags by default in the "Release" configuration though. But if you'd want to use these flags to remove some other assertions, you'd also be removing all your "object creation succeeded" checks.
Edit: Upon further reflection, it seems more plausible than I first thought that [NSMutableArray arrayWithCapacity: n] would return nil rather than abort the application when not enough memory is available. Basic C malloc also doesn't abort but returns a NULL pointer when not enough memory is available. But I haven't yet found any clear mention of this in the Objective-C documentation on alloc and similar methods.
Edit: Above I said I wasn't sure checking for nil is necessary at every object creation. But it shouldn't be. This is exactly why Objective-C allows sending messages to nil, which then return nil (or 0 or something similar, depending on the message definition): this way, nil can propagate through your code somewhat similar to an exception so that you don't have to explicitly check for nil at every single message that might return it. But it's a good idea to check for it at points where you don't want it to propagate, like when writing files, interacting with the user and so on, or in cases where the result of sending a message to nil is undefined (as explained in the documentation on sending messages to nil). I'd be inclined to say this is like the "poor man's" version of exception propagation&handling, though not everyone may agree that the latter is better; but nil doesn't tell you anything about why an error occurred and you can easily forget to check for it where such checks are necessary.
Yup. I think it's a good idea.. It helps to filter out the edge cases (out of memory, input variables empty/nil) as soon as the variables are introduced. Although I am not sure the impact on speed because of the overhead!
I guess it's a matter of personal choice. Usually asserts are used for debugging purpose so that the app crashes at the assert points if the conditions are not met. You'd normally like to strip them out on your app releases though.
I personally am too lazy to place asserts around every block of code as you have shown. I think it's close to being a bit too paranoid. Asserts might be pretty handy in case of conditions where some uncertainity is involved.
I have also asked this on Apple DevForums. According to Quinn "The Eskimo!" (author of the MVCNetworking sample in question) it is a matter of coding style and his personal preference:
I use lots of asserts because I hate debugging. (...)
Keep in mind that I grew up with traditional Mac OS, where a single rogue pointer could bring down your entire machine (similarly to kernel programming on current systems). In that world it was important to find your bugs sooner rather than later. And lots of asserts help you do that.
Also, even today I spend much of my life dealing with network programs. Debugging network programs is hard because of the asynchrony involved. Asserts help to with this, because they are continually checking the state of your program as it runs.
However, I think you have a valid point with stuff like +[NSDate date]. The chances of that returning nil are low. The assert is there purely from habit. But I think the costs of this habit (some extra typing, learning to ignore the asserts) are small compared to the benefits.
From this I gather that asserting that every object creation succeeded is not strictly necessary.
Asserts can be valuable to document the pre-conditions in methods, during development, as design aid for other maintainers (including the future self). I personally prefer the alternative style - to separate the specification and implementation using TDD/BDD practices.
Asserts can be used to double-check runtime types of method arguments due to the dynamic nature of Objective C:
assert([response isKindOfClass:[NSHTTPURLResponse class]]);
I'm sure there are more good uses of assertions. All Things In Moderation...
I'm supporting 10.4+ by picking the most-current API at runtime:
if ([fileManager respondsToSelector:#selector(removeItemAtPath:error:)])
[fileManager removeItemAtPath:downloadDir error:NULL];
else
[fileManager removeFileAtPath:downloadDir handler:nil];
In this case, 10.5 and up will use removeItemAtPath:error: and 10.4 will use removeFileAtPath:handler:. Great, but I still get compiler warnings for the old methods:
warning: 'removeFileAtPath:handler:' is deprecated [-Wdeprecated-declarations]
Is there a syntax of if([… respondsToSelector:#selector(…)]){ … } else { … } that hints the compiler (Clang) to not warn on that line?
If not, is there a way to tag that line to be ignored for -Wdeprecated-declarations?
After seeing some of the answers, let me clarify that confusing the compiler into not knowing what I'm doing is not a valid solution.
I found an example in the Clang Compiler User's Manual that lets me ignore the warning:
if ([fileManager respondsToSelector:#selector(removeItemAtPath:error:)]) {
[fileManager removeItemAtPath:downloadDir error:NULL];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[fileManager removeFileAtPath:downloadDir handler:nil];
#pragma clang diagnostic pop
}
You could declare a separate file that is designated for calling deprecated methods and set the per-file compiler flags in Xcode to ignore -Wdeprecated-declarations. You can then define a dummy function in that file to call the deprecated methods, and thereby avoid the warnings in your real source files.
I'm not sure if clang is smart enough to catch this, but if it's not, you could try using performSelector:withObject:withObject: or building and invoking an NSInvocation object.
You could just cast fileManager to an id — ids are able to refer to any Objective-C object, so the compiler isn't supposed to check methods which are called on one:
[(id)fileManager removeItemAtPath:downloadDir error:NULL];
shouldn't raise any warnings or errors.
Of course, this raises other problems — namely, you lose all compile-time checking for methods called on the id. So if you misspell you method name, etc, it wont be caught until that line of code is executed.
If you consider any form of "confusing" the compiler to be an invalid solution, you're probably going to have to live with the warning. (In my book, if you asking how to get rid of a warning, it's unwise to look a gift horse in the mouth and say something is invalid just because it doesn't look like you'd expect.)
The answers that work at runtime involve masking the operation that's happening with dynamic dispatch so the compiler doesn't complain about the deprecated call. If you don't like that approach, you can turn off "Warn About Deprecated Functions" in your Xcode project or target settings, but that's generally a bad idea. You want to know about deprecated APIs, but in this case you want to use it without warning. There are easy and hard ways to do this, and odds are you'd consider all of them "invalid" in some form, but that doesn't prevent them from being effective, even correct. ;-)
One possible way to avoid the warnings yet still select at runtime is to use objc_msgSend() directly:
objc_msgSend(fileManager, #selector(removeFileAtPath:error:), downloadDir, nil];
This is what the Objective-C runtime does under the covers anyway, and should accomplish the result you want with a minimum of fuss. You can even leave the original line commented above it for clarity. I know the documentation says, "The compiler generates calls to the messaging function. You should never call it directly in the code you write." You alone have to decide when it's okay to bend the rules.
EDIT: I have fixed all but two warnings now, so thank you all for the advice and the encouragement. The two warnings I have left would require me to change the database:
/Locations.xcdatamodel:tiles.Map: warning: tiles.Map -- relationship does not have an inverse
/Locations.xcdatamodel:Waypoint.description: warning: Waypoint.description -- property name conflicts with a method already on NSObject or NSManagedObject
I have an iPhone app that throws more than 100 warnings when I compile it, but it is time-tested and solid.
Should I care about warnings?
EDIT Because the respondents asked, here are some of my warnings:
Warning: Multiple build commands for output file /Users/andrewljohnson/Desktop/thetrailbehind/TrailTracker/build/Debug-iphonesimulator/Gaia Places.app/wrench.png
/Locations.xcdatamodel:tiles.Map: warning: tiles.Map -- relationship does not have an inverse
/Locations.xcdatamodel:Waypoint.description: warning: Waypoint.description -- property name conflicts with a method already on NSObject or NSManagedObject
/TrailTrackerAppDelegate.m:58: warning: passing argument 1 of 'initWithViewController:withTitle:' from distinct Objective-C type
/Users/andrewljohnson/Desktop/thetrailbehind/TrailTracker/Classes/TrailTrackerAppDelegate.m: In function '-[TrailTrackerAppDelegate applicationDidFinishLaunching:]':
/Users/andrewljohnson/Desktop/thetrailbehind/TrailTracker/Classes/TrailTrackerAppDelegate.m:202: warning: no '-initWithFrame:forHelpScreen:' method found
/Users/andrewljohnson/Desktop/thetrailbehind/TrailTracker/Classes/TrailTrackerAppDelegate.m:202: warning: (Messages without a matching method signature
/TrailTrackerAppDelegate.m:329: warning: 'gpsController' may not respond to '-setAccuracy:'
/Users/andrewljohnson/Desktop/thetrailbehind/TrailTracker/Classes
/TrailTrackerAppDelegate.m:411: warning: local declaration of 'tabBarController' hides instance variable
/TrailTrackerAppDelegate.m:422: warning: 'TrailTrackerAppDelegate' may not respond to '-getAudioPlayer:'
/Users/andrewljohnson/Desktop/thetrailbehind/TrailTracker/Classes/TrailTrackerAppDelegate.m:633: warning: 'Reachability' may not respond to '-isHostReachable:'
/Users/andrewljohnson/Desktop/thetrailbehind/TrailTracker/Classes/TrailTrackerMapView.h:18: warning: 'myTopoMapSource' defined but not used
warning: 'dbCache' defined but not used
/TrailTrackerAppDelegate.m:58: warning: passing argument 1 of 'initWithViewController:withTitle:' from distinct Objective-C type
/Users/andrewljohnson/Desktop/thetrailbehind/TrailTracker/Classes
/Users/andrewljohnson/Desktop/thetrailbehind/TrailTracker/Classes/TripViewController.m:68: warning: 'TripViewController' may not respond to '-checkForNullImages'
/Users/andrewljohnson/Desktop/thetrailbehind/TrailTracker/Classes/TripViewController.m:94: warning: 'TrailTrackerAppDelegate' may not respond to '-blamblamblam'
/Users/andrewljohnson/Desktop/thetrailbehind/TrailTracker/Classes/MapViewController.m:406: warning: passing argument 1 of 'initWithData:' from distinct Objective-C type
Yes. Some Warnings can be important.
It's best practice to turn a compiler's warning level to the highest setting, and to try to eliminate all warnings.
If a warning cannot be removed through refactoring code, and it has been checked and deemed safe, then many languages have 'pragmas' to silence the warning.
Update circa 2014: It is increasingly common to turn on a complier option that treats all warnings as errors. I personally do this.
My gut answer would be absolutely, wholeheartedly yes.
Compiler warnings are there to help you write clear and maintainable code, reducing the likelihood of bugs being introduced later on or cropping up at runtime.
The compiler will generally catch things like unused variables, access to uninitialised variables, failure to return correctly from a function, etc. These things may not be an issue now or in testing, but could easily come along and screw you later.
I would be going through those warnings and trying to fix them now. It will be time well spent.
Many of those warnings look like extraneous stuff in your program that's harmless. However, when you have 100 warnings you know don't matter (I'm not saying all of those don't matter, I'm just illustrating) and warning 101 that's very real shows up--the odds are you aren't going to see it.
I do not tolerate any warnings whatsoever. Occasionally this means adding a useless line or two of code because the compiler can't see that a conditional must execute or the like. (A case in front of me as I write this: 4 paths in a switch on a random number. 1 of the 4 must execute and each assigns a value to a variable. The compiler doesn't know it must have a value at that point so I added an extraneous assignment to shut it up.)
lol I guess it depends what the warnings are!!
If you have over 100 and yet it runs just fine, I'd guess that they are probably warnings of the type "Object xxx may not respond to message yyy" - i.e. the new methods you've created within your app have not been set up with an appropriate declaration in the header so your compiler isn't able to check whether they are valid method calls for (or more accurately, messages to send to) your custom classes.
Many warnings in objective-C actually warn you of an error that will crash the application - in fact, there is even an option within XCode to "treat all warnings as errors". The fact that your app runs shows that you are not suffering from this problem (or at least, have not yet).
However, even if all your warnings are benign (which I doubt), there is good reason for fixing them. If its regarding class methods, you'll be able to find out before you experience a crash whether or not your sending a valid message to it. And for most of the other types of warnings, you're better off knowing about it.
I guess the final exception is if you're using a lot of deprecated methods. Then you might decide to leave them be, although again that's a risky strategy.
So we're back to the beginning point - it depends what they are! However, I'm 99% sure that it will be a worthwhile exercise fixing them. They're there to help you, not it!
Definitely Yes. Otherwise why would it be called a Warning?
If I could give ObjC developers one piece of advice, it would be "use accessors, always." But if I could give them two pieces of advice, the second piece would be "turn on 'treat warnings as errors'."
Maintaining a zero warning policy in Cocoa is perhaps the best cost/benefit trade-off I know of. There are very few warnings that cannot be fixed easily in Cocoa. When writing portable C++, it is often very challenging (sometimes nearly impossible) to avoid warnings, but Cocoa has a single compiler on two very similar platforms. There's almost nothing you need to be doing in Cocoa that should be tripping the default warning set.
Warnings breed warnings. When you say "well, I know about those 121 warnings and they're ok," it's very easy to miss when it becomes 122 warnings and that new one does matter. If you have a warning that you really need to work around, then suppress the warning, but don't ignore them in the build output.
My team turns up warnings very high, and over time we've had to tune them back down a little bit, but we still build major Objective-C++ projects on Mac and iPhone under the following warning flags. There are a few of them that could certainly come out for a particular project, but this is my team's default set, and we don't take many out. I talk about it a little more in my discussion of project templates. The zip file there includes Shared.xcconfig which documents what each of these does and why it's turned on or off. But the default set that Xcode gives is a minimum.
GCC_TREAT_WARNINGS_AS_ERRORS = YES
WARNING_CFLAGS = -Wall -Wextra -Wno-missing-field-initializers -Wno-unused-parameter -Wno-unknown-pragmas -Wextra-tokens -Wformat-nonliteral -Wformat-security -Winit-self -Wswitch-enum -Wswitch-default -Wfloat-equal -Wpointer-arith -Wredundant-decls -Winvalid-pch -Wlong-long -Wdisabled-optimization
OTHER_CFLAGS = -Wnested-externs -Wold-style-definition -Wstrict-prototypes -Wundeclared-selector
OTHER_CPLUSPLUSFLAGS = -Wsign-promo -Wundeclared-selector
GCC_WARN_CHECK_SWITCH_STATEMENTS = YES
GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES
GCC_WARN_64_TO_32_BIT_CONVERSION = YES
GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES
GCC_WARN_ABOUT_RETURN_TYPE = YES
GCC_WARN_MISSING_PARENTHESES = YES
GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES
GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES
GCC_WARN_SIGN_COMPARE = YES
GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES
GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES
GCC_WARN_UNUSED_FUNCTION = YES
GCC_WARN_UNUSED_LABEL = YES
GCC_WARN_UNUSED_VALUE = YES
GCC_WARN_UNUSED_VARIABLE = YES
GCC_WARN_UNINITIALIZED_AUTOS = YES
Absolutely. You should always resolve your warnings. If you can't, you should at least know why the warning is there and why you can ignore it. To just ignore all compiler messages, (however innocuous as they may seem), is just a recipe for disaster.
YES