__attribute__ ((deprecated)) does not work on objective-c protocol methods? - objective-c

I need to deprecate a single method in objective-c protocol. On normal class/instance methods I add __attribute__ ((deprecated)); after declaration.
It seems, that it does not work on protocol methods. If I mark them deprecated and use them somewhere the project compiles OK, without expected deprecation warning.
Is it a flaw in Apple LLVM 3.1, or am I doing something wrong?

Although the answers here provide some very good information, they are outdated. Starting with Xcode 5.0 and LLVM 5.0 it looks like deprecation warnings for Objective-C protocol methods are recognized. When implementing the method, Xcode 5 flags it:
Warning: Implementing deprecated method
Here are the steps I used to produce a deprecation warning for the implementation of a deprecated protocol method:
Mark the protocol method as deprecated using __deprecated. From the new SDK 7.0 documentation:
__deprecated causes the compiler to produce a warning when encountering code using the deprecated functionality. __deprecated_msg() does the same, and compilers that support it will print a message along with the deprecation warning. This may require turning on such warning with the -Wdeprecated flag. __deprecated_enum_msg() should be used on enums, and compilers that support it will print the deprecation warning.
#define __deprecated __attribute__((deprecated))
To deprecate your method, do something like this:
- (void)aDeprecatedProtocolMethod __deprecated;
This alone should be enough for Xcode to display a deprecation warning. However, you should follow the next few steps (knowing that Xcode can be very finicky at times) to ensure the warning displays.
Add a documentation comment with a deprecation warning tag. See the code example below to learn how:
/** Describe the method here - what does it do, how does it work, etc. Very brief.
#deprecated This delegate method is deprecated starting in version 2.0, please use otherMethodNameHere:withAnExtraParameter: instead. */
- (void)aDeprecatedProtocolMethod __deprecated;
Clean the project (⌘+⇧+K) and then Build the project (⌘+B) - just because Xcode can be funky sometimes.
I'm not 100% sure when or where this feature was introduced (maybe with SDK 7.0 and 10.9, or Xcode 5.0 / 5.0.1, or with LLVM 5.0) - but it works nonetheless.

Well, I just realised, that even Apple use __attribute__((deprecated)) at the end. And it does not work either. If I use any deprecated delegate method, e.g.
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView
accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
there is no warning.
So it seems like a candidate for radar.
EDIT: filed a radar, Bug ID# 11849771.

Apple deprecated some methods in the UITableViewDelegate protocol, perhaps you'll be able to find the solution using Apple's code as example.
The relevant code of the protocol is as follows:
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView
accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_2_0,__IPHONE_3_0);
As you can see, Apple uses a macro. Perhaps this is the way to go?
EDIT: As noted on the following link [1] __attribute__((deprecated)) is a GCC construct so this might not work in LLVM. I guess this is the reason Apple uses macros, so some other (or no) deprecation construct will be called when other compilers are used.
[1] How to deprecate a method in Xcode

Related

Why does objective-c not have API availability checking?

Swift 2 have API availability checking.
The compiler will give you an error when using an API too new for your
minimum target OS
Why can't the objective-c compiler do the equivalent?
I googled objective c API availability checking and only swift 2 results came out so I assume the compiler for objective c can't do that.
Xcode 9.0 brings the runtime availability checking syntax from Swift to Objective-C:
if (#available(macOS 10.9, *))
{
// call 10.9+ API
}
else
{
// fallback code
}
this comes complete with warnings for calling APIs that are newer than your deployment target (if those calls are not wrapped in checks).
finally ;)
The warning (Swift makes it an error) just hadn't been implemented in the Clang compiler for years, but it's not an inherent Objective-C limitation (although due to its dynamic nature, you won't be able to catch all cases), nor Swift terminology.
The Apple macros (e.g., NS_CLASS_AVAILABLE) and source attributes (__attribute__((visibility(...))), __attribute__((availability(...)))) to annotate headers with availability information have been there for years, and they are widely-used in Apple's SDKs. The macros are defined in Foundation's NSObjCRuntime.h, and the Availability.h/AvailabilityMacros.h system headers, and the compiler can (and does) read them.
In early 2015, the -Wpartial-availability warning has been added to Clang's master branch, but this commit/warning hadn't made its way into Apple's version of Clang until (including) Xcode 7.2. You will get an unknown warning option log when adding the warning flag to a project in Xcode 7.2, but the flag is available in Xcode 7.3. There's currently no predefined setting for it, but you can add the flag to Other Warning Flags under Build Settings.
There are other tools that use LLVM libraries to detect partially available APIs, e.g., Deploymate. For my diploma thesis, I developed a tool that integrates directly into Xcode and is based on a modification to the Clang compiler. The code is still online, but I haven't kept up with the general Clang development so it won't be of much use, except for learning purposes. However, the "official" code (linked above) is much cleaner and better.
Edit: Starting with Xcode 9, availability checking will work for Objective-C (and C), too. Instead of using the above-mentioned warning flag, which does not support raising the deployment target temporarily/locally and therefore causes plenty of false positives, there's -Wunguarded-availability, and if (#available(iOS 11, *)) {...} to check and raise the deployment target for the following block of code. It is off by default, but -Wunguarded-availability-new will be on by default, and starts checking anything beyond iOS/tvOS 11, watchOS 4, and High Sierra. More details on that can be found in the Xcode 9 beta release notes, which currently requires signing in with a developer account.
Objective C does not have availability checking as part of the language, as the same result is available via Objective C preprocessor.
That is the "traditional" way of doing that in C derived languages.
Want to know if compiled in debug mode?
#ifdef DEBUG
// code which will be inserted only if compiled in debug mode
#endif
Want to check at compile time for a minimum version?
Use the Availability.h header in iOS, and similar headers for Mac OS X.
This file reside in the /usr/include directory.
just test __IPHONE_OS_VERSION_MAX_ALLOWED with the preprocessor, e.g.:
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([application respondsToSelector:#selector(registerUserNotificationSettings:)]) {
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil]];
}else{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert)];
}
#else
[[UIApplication sharedApplication] registerUserNotificationSettings: (UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert)];
#endif
As Swift does not have a preprocessor, they had to invent a way of doing these kind of checks within the language itself.
If you want to check availability of a method at runtime, please notice that the appropriate way is by using the method respondsToSelector:, or instancesRespondToSelector: (the latter at class level).
You will normally want to combine both approaches, compile time conditional compilation and runtime check.
Objective C method presence verification, e.g. at class level:
if ([UIImagePickerController instancesRespondToSelector:
#selector (availableCaptureModesForCameraDevice:)]) {
// Method is available for use.
// Your code can check if video capture is available and,
// if it is, offer that option.
} else {
// Method is not available.
// Alternate code to use only still image capture.
}
If you want to test if a C function exists at runtime, it is even simpler: if it exists, the function itself it is not null.
You can't use the same identical approach in both languages.
It does these days. Furthermore, with Xcode 11 (including the current Xcode 11.3.1), you can even get it from the snippets. Press the + button towards the top right of Xcode (as shown in the image below).
Then in the search box, type "API". All 3 versions of the snippet for API Availability Check will appear -- Objective C, C and Swift.
Of course, you will get errors in Objective-C code. But you won't find results in google for Objective-C, if you use a term defined for Swift as you will not find kisuaheli website in google if you search for a german word. ;-)
You will get an error linking Objective-C code against a too old SDK. This is simply because the used method or class or $whatever is not defined in the header for that SDK. Again, of course.
This is typical Swift marketing of Apple: Because of the incapability of Swift they have to extend the language to get something, which is quite easy in Objective-C. Instead of clarifying that this is the result of the poorness of Swift, they tell you that this is a great feature of Swift. It is like cutting your fingers and then saying: "We have the great plaster feature!!!!!!!!" And you have to wait only some days and one comes around on SO with the Q: "Why does Objective-C does not have the great plaster feature???????" The simple answer: It does not cut your fingers.
The problem is not to generate the errors. The problem is to have one source code for all versions, so you can simply change the SDK version and get new code (or errors). You need that for easier maintenance.
In Objective-C you simply can use the answer found here:
Conditionally Hide Code from the Compiler or you can do that at runtime as mentioned in the comments to the Q. (But this is a different solution of the problem by nature, because it a dynamic approach instead of a static one as you have to do in Swift.)
The reason for having a language feature in Swift is that Swift has no preprocessor, so the Objective-C solution would not work in Swift. Therefore conditional code would be impossible in Swift and they had to add the plaster, eh, language feature.

NSUUID conflict (iOS6.0 and Above)

We have a NSUUID class (we provide the declaration and implementation). We used it successfully up to iOS 6.0. We implemented it because UIDevice uniqueIdentifier was banned long before Apple deprecated it, and returning a NSUUID was a natural choice.
At iOS 6.0, we had to guard the define because Apple introduced the same class:
#if __IPHONE_OS_VERSION_MAX_ALLOWED <= __IPHONE_5_1
#interface NSUUID : NSObject {
...
}
#endif
iOS 5.1 and lesser are now broken. On iOS 5.1, we get back nil after alloc/init.
I tried to remove the #if/#end, but I get duplicate names when using the latest iPhone SDK.
Apple's lack of a stable API is a bug, not a feature. This "try it at runtime" crap is not cutting it. It makes it very difficult to write high integrity software.
From Tommy's response below, I can't instruct Apple's toolchain to use our implementation of NSUUID all the time. How do I provide an implementation of NSUUID for iOS 5.1 and lower (that might be compiled using the latest SDK)?
You can't. You've explicitly broken the rules:
Objective-C classes must be named uniquely [...] In order to keep
class names unique, the convention is to use prefixes on all classes.
You’ll have noticed that Cocoa and Cocoa Touch class names typically
start either with NS or UI. Two-letter prefixes like these are
reserved by Apple for use in framework classes.
You'll need to rename your own class. The quickest way is quite probably to right click on the class name, select "Refactor -> Rename..." and use a correct prefix this time. Xcode may not be able to refactor fully automatically since it'll obviously be ambiguous which NSUUID you're referring to in other parts of your code.
EDIT: regardless of grandstanding, if you want to implement code that provides a self-implemented replacement for NSUUID where it's not available then the solution is to "try it at runtime".
Assuming you've implemented NDRUUID, which implements the same interface as NSUUID then the quickest solution is to add something like this to your prefix header:
#define NSUUID (NSClassFromString(#"NSUUID") ? [NSUUID class] : [NDRUUID class])
You can then use [NSUUID UUID], etc, everywhere else in your code as though you were targeting iOS 6 only; the only difference is that when running under 5 you'll actually be addressing NDRUUID. Whenever you stop supporting 5 just remove that line from your prefix header and delete your own class from the project.
Hopefully you can see this is a much better way to handle introducing new APIs and backwards compatibility than, say, not using Apple's NSUUID at all anywhere until it's available everywhere.
I have built exactly what you asked for: an implementation of NSUUID for iOS 5.1 and lower that might be compiled using the latest SDK. See my NSUUID project on GitHub.

How can i use Objective-C's Property feature in GNUstep?

I'm trying to use Objective-C 2.0 feature Property in GNUstep(using Windows).
But i can't use #property sign and #synthesize.
Although All of my codes are correct,compiler can't compile my property code.
Compiler also can't understand "#" sign.
Can i use Property feature in GNUstep.
If it's can use,Please tell me how can i do that?
Thanks you for your time.
The GNUStep GCC compiler does not support #property (or any of the the other Objective-C 2.0 language changes). However, if you can use Clang, you have access to Objective-C 2.0 features at compilation. As long as you can find an Objective-C 2.0-compatible runtime, you're all set. See http://wiki.gnustep.org/index.php/ObjC2_FAQ#Which_Bits_of_Objective-C_2_Work.3F.
Now you can use Clang 3.3 + libobjc2 + GNUstep to compile all the current Objective-C 2.0 language features. (blocks/ARC/properties...)
But if you're on Windows, I think you may have some trouble to run Clang...
Quick answer is that out-of-the-box, you can't. Version 2.0 of the language specification is specific to Apple's implementation. See here for a summary.

Xcode/iOS -- get rid of deprecation warnings for specific constants?

I have some deprecated constants in my project. They need to stay. I don't want to be warned about them, but do want to be warned if other deprecated constants should turn up in my project later.
Apple's header declares them as follows:
extern NSString * const NameOfStringConstant __OSX_AVAILABLE_BUT_DEPRECATED(version availability info here)
How can I silence the warning?
Related answer for silencing the warning for a deprecated method here
Related answer for silencing the warning about a deprecated string conversion here
I know this is an old topic but today i was dealing with the same annoyance.
Example: you want to get rid of the annoying deprecation warning but just for [[UIDevice currentDevice] uniqueIdentifier]] since you most probably want to use it in development phase with TestFlight.
You'd still want the compiler to warn you if you use some other deprecated declaration by mistake.
I like sarfata's answer: it does the job. But there's more politically correct way available:
Following recipe is taken from The Goo Software Blog.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[TestFlight setDeviceIdentifier:[[UIDevice currentDevice] uniqueIdentifier]];
#pragma clang diagnostic pop
Make sure you comment out this lines before building for distribution. Or simply use a preprocessor macro to exclude this lines from a release build.
Add to the compiler flags:
-Wno-deprecated-declarations
or, in Xcode, select "No" for the build setting option:
Warn About Deprecated Functions
and then if you look at the build output (Apple+7 in Xcode 4), you'll notice the aforementioned compiler flag.
The proper answer to this question is to not use deprecated constants. Check the documentation for the recommended way to accomplish something now. On the deprecated methods/constants/whatever, there's almost always a link to the "replacement" if you will. Use that instead. This way your code doesn't mysteriously break when those disappear forever, but your users still have a build built against the old sdk, and now their code crashes, or worse, does weird things.
This is #1 answer in google and I believe there are some faire case when using a deprecated method is useful and when you want to avoid warnings to keep the build "clean". This solutions is inspired by: http://vgable.com/blog/2009/06/15/ignoring-just-one-deprecated-warning/
The idea is to declare a new protocol that has the same method (but not deprecated of course) and to cast the object to that protocol. This way you can call the method without getting the warning and without getting rid of all the deprecation warnings.
Exemple: If you want to integrate TestFlight in your application, the SDK documentation suggests transmitting the uniqueIdentifier of the device while in BETA. This can help track which tester had problems. This method is deprecated by Apple (and they will not let you submit the app) but I believe this is a good example of using a deprecated method.
In your App Delegate:
/* This is to avoid a warning when calling uniqueIdentifier for TestFlight */
#protocol UIDeviceHack <NSObject>
- (NSString*) uniqueIdentifier;
#end
#implementation MyAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[TestFlight takeOff:#"Your-Testflight-team-id"];
// TODO: Remove this in production (forbidden APIs) - Used here to improve beta reporting.
[TestFlight setDeviceIdentifier:[(id<UIDeviceHack>)[UIDevice currentDevice] uniqueIdentifier]];
// ...
}

Objective-C : Properties question

As far as I understand when you use properties the compiler still converts them to accessor methods during compilation. I got a little irritated when I read you need OSX 10.5 or later to use properties. Why is that so?
If in the compiled application are in fact still accessor methods I see no need for OSX 10.5. Or is there something else going on during run-time?
Because the Objective-C 2.0 runtime was not back ported to 10.4. You need compiler and runtime support to handle all of ObjC 2.0 properly.