Semantic Issue: Property's synthesized getter follows Cocoa naming convention for returning 'owned' objects - objective-c

I'm currently using the iOS 5 SDK trying to develop my app.
I'm trying to make an NSString a property, and then to synthesize it in the .m file (I have done this before with no issues). Now, I came across this: "Semantic Issue: Property's synthesized getter follows Cocoa naming convention for returning 'owned' objects."
This is my code:
.h
#interface ViewController : UIViewController {
NSString *newTitle;
}
#property (strong, nonatomic) NSString *newTitle;
.m
#synthesize newTitle;
Does anyone have a clue how I could fix this?
Thanks!!

My guess is that the compiler version you’re using follows the memory management rules for declared properties, too — more specifically, for declared properties’ accessors:
You take ownership of an object if you create it using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy”.
A property named newTitle, when synthesised, yields a method called -newTitle, hence the warning/error. -newTitle is supposed to be a getter method for the newTitle property, however naming conventions state that a method whose name begins with new returns an object that’s owned by the caller, which is not the case of getter methods.
You can solve this by:
Renaming that property:
#property (strong, nonatomic) NSString *theNewTitle;
Keeping the property name and specifying a getter name that doesn’t begin with one of the special method name prefixes:
#property (strong, nonatomic, getter=theNewTitle) NSString *newTitle;
Keeping both the property name and the getter name, and telling the compiler that, even though the getter name starts with new, it belongs to the none method family as opposed to the new method family:
#ifndef __has_attribute
#define __has_attribute(x) 0 // Compatibility with non-clang compilers
#endif
#if __has_attribute(objc_method_family)
#define BV_OBJC_METHOD_FAMILY_NONE __attribute__((objc_method_family(none)))
#else
#define BV_OBJC_METHOD_FAMILY_NONE
#endif
#interface ViewController : UIViewController
#property (strong, nonatomic) NSString *newTitle;
- (NSString *)newTitle BV_OBJC_METHOD_FAMILY_NONE;
#end
Note that even though this solution allows you to keep newTitle as both the property name and the getter name, having a method called -newTitle that doesn’t return an object owned by the caller can be confusing for other people reading your code.
For the record, Apple have published Transitioning to ARC Release Notes, in which they state:
You cannot give a property a name that begins with new or copy.
They’ve already been notified that their statement is not quite accurate: the culprit is the getter method name, not the property name.
Edit 17 Jan 2015: I’ve just noticed a recent commit to Clang that suggests option 3 above (using objc_method_family(none)), including a fix-it, for the general case where a property name matches one of the special method family prefixes. Xcode will likely incorporate this change eventually.

Unacceptable Object Names
newButton
copyLabel
allocTitle
Acceptable Object Names
neueButton
mCopyLabel
_allocTitle
#arc #auto-synthesized #xcode-4.6.1
** EDIT **
Apparently you can't use mutableCopy either.

The name of the member starting with new is what triggers the warning. Change the name to editedTitle and the warning will go away. I was unable to find documentation confirming this but through testing was able to determine that member variables that begin with 'new' aggravate the compiler.

ARC does not allow to use "New...." in property name. but you can use "newTitle" by changing getter name.
#property (nonatomic, strong, getter=theNewTitle) NSString *newTitle;

It doesn't look like what Bavarious was suggesting was what you wanted to do. All you want to do is declare an instance variable NewTitle and then synthesize the property. We used to have to declare the instance variable and property. No more.
Now, I believe the right way of doing this is the following:
.h
#interface ViewController : UIViewController
#property (nonatomic, strong) NSString *newTitle;
.m
#synthesize newTitle = _newTitle; // Use instance variable _newTitle for storage
The instance variable for the property newTitle is synthesized. You don't want your instance variable to be the same as your property - too easy to make mistakes.
See Example: Declaring Properties and Synthesizing Accessors

In CoreData if you use "new..." in attribute (compile normally) it will crash randomly with a "bad access" exception.
There is no crash log and the line shown with the "All Exceptions Breakpoint" will not help you at all.

Writing a setter manually with the name same as the property's removed this warning.

NS_RETURNS_NOT_RETAINED is used to solve the naming problem.
#property (nonatomic, copy) NSString *newTitle NS_RETURNS_NOT_RETAINED;
We can find its definition as follows:
#define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained))
The 'ns_returns_not_retained' attribute is the complement of 'ns_returns_retained'. Where a function or method may appear to obey the Cocoa conventions and return a retained Cocoa object, this attribute can be used to indicate that the object reference returned should not be considered as an "owning" reference being returned to the caller. The Foundation framework defines a macro NS_RETURNS_NOT_RETAINED that is functionally equivalent to the one shown below.

Besides the issue that you should/can't use "new" in front of you property names, let say one more thing: Try to avoid "new" in front of names in general. "New" is dependent on time. Currently it is new for you, but some time later you maybe want to implement something new again. So using "new" in names is always bad. Try to think this way: In the programming world, "new" is always creating something: a new instance of something.
In your case when you want to assign a different title then the current name your property titleReplacement.
One more thing: Try to name functions and methods with the verb first, like setSomething or getSomething.
But in properties try to name the object first, like heightMinimum, heightMaximum, etc. -> when you use your inspector when you are coding, you always looking for objects. Try it out. ;-)

try this:-
#property (nonatomic,retain) NSString *newTitle;

Related

difference between a variable with and without an underscore in objective-c [duplicate]

This question already has answers here:
How does an underscore in front of a variable in a cocoa objective-c class work?
(9 answers)
Closed 9 years ago.
In the tutorial i am following, it creates a property of an array like so
#property (nonatomic, retain) NSMutableArray *entries;
And in the implementation file and defines it defines it as...
entries = [[NSMutableArray alloc] init];
However in my program, defining like that gives me an error
"Use of undeclared identifier 'entries'; did you mean '_entries'?"
Does this affect my program?
In simple:
#property (nonatomic, retain) NSMutableArray *entries;
creates the following code for you:
An ivar called _entries and two methods
- (void)setEntries:(NSMutableArray *)entries;
- (NSMutableArray *)entries;
If you want to give the ivar a different name (e. g. entries without underscore) you have to synthesize them. But you hardly ever need the actual, just use your properties like self.entries.
The rare cases where you actually want the ivar is when you want to override the setter and getter method
- (void)setEntries:(NSMutableArray *)entries
{
_entries = entries;
// do more stuff
}
When you declare property compilator create private variable which you can access with underscore (_entries) and compilator also create setter (if you do not specify readonly) and getter. You can call getter in two ways:
[self entries] or self.entries
When you declare property you should access in it two ways:
_entries - You access your private variable directly (can be use just inside the class)
self.entries - You can access this property view setter/getter it's safe way because this method manage way how to access it (release, retain, copy, etc.)
#property (nonatomic, retain) NSMutableArray *entries; is nothing but an instance variable of name _entries. (or any other name, that you can specify while doing the synthesize)
When you do #synthesize entries, two accessor methods (setter and getter) are created for you
- (void)setEntries:(NSMutableArray *)entries;
- (NSMutableArray *)entries;
If you access it directly as _entries, then it is just changing the value of the variable.
But if you say self.entries, the accessor methods are called. The accessor methods are made according to what property type you specified, strong (or retain) copy assign atomic, say assign will just copy the value to the variable, atomic makes sure that if setter and getter are called together from different threads, getter always gets the value either prior to the start of setter or after the completion of setter.

Key-Value Coding with a key of 'description'

I am using Key-Value Coding to simplify updating instances of a model class:
#interface NewsItem : NSObject
{
}
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSString *description;
#property (nonatomic, copy) NSString *link;
#property (nonatomic, copy) NSString *date;
using:
SEL selectorName = NSSelectorFromString(elementName);
if ([self.newsItem respondsToSelector:selectorName])
{
NSString *sanitisedElement = [self sanitiseElement:self.currentElementData];
[self.newsItem setValue:sanitisedElement forKey:elementName];
}
This works well but the 'description' property doesn't 'smell' right to me as it has overridden the base NSObject description getter (+ (NSString *)description). If the description getter is invoked now it will return irrelevant information when the caller would be expecting a description of the class.
Is it possible to safely proceed with Key-Value Coding for this class (given that I am bound to these property names by the external data source)? Or would it be wise to change the property names and manually check keys/set values instead?
You could override description in your class. This method is usually used only for debugging
and no caller can expect a specific output of that method.
But I see more general problems in your code. It is only checked that a method with the
given name exists. This does not imply that this method corresponds to a property, and even then, it does not imply that there is a setter for that property.
For example, every NSObject responds to the selector "init", so if the external
data source sends that key as "elementName", your code would immediately crash.
Therefore, an explicit list of "known keys" is needed. But then you can as well
use a mapping (NSDictionary) from external element names to internal properties
to avoid any conflicts.
I think that you are confusing methods with properties, and you are making things more complicated that how they are.
Is enough that, given an elementName that contains directly the setter name (i.e.: setDate), you invoke the selector passing that argument the object argument:
SEL selectorName = NSSelectorFromString(elementName); // elementName something like "setDate"
if ([self.newsItem respondsToSelector:selectorName])
{
[self.newsItem performSelector: selectorName withObject: sanitisedElement];
}
As for the description method, it has overridden NSObject's description, so you have two choices: name it in another way, or leave it like it is, and invoke it on super when you need the object description, with the help of Objective-C runtime:
struct objc_super superclass= { self.newItem, [self.newItem superclass] };
NSString* desc= objc_msgSendSuper(&superclass, #selector(description));
You can always override inherited methods.
By creating a property whose getter is the same as the signature of An inherited method, you are overriding it.
Is it bad? Yes if your implementation is not useful for debugging.
As best practice for KVC and KVO purposes it is a good idea to avoid potentially clashing with common inherited methods properties and ivars.
The common approach to this is to make longer property and method names and to make them more likely to be unique. One common way is by prefixing all yours with an abbreviation common to your class or framework or code.
Using something commonly used by Apple is likely to bite you in a rare and hard to debug way.
It's especially a bad idea to do this when core data is involved.
Don't be reluctant to make things longer. Code completion will type for you. Plus, a nice side effect of class specific prefixing is pseudo not only the pseudo namespace but that your class specific properties, variables, constants and methods will bubble up first in code completion.

do category allow addition of instance variables in its implemenation?

I am working ios6.0 sdk with xcode 4.5.2
Here is following code i used to implement a category
.h
#interface NSObject (busyMode)
#property (nonatomic,assign) BOOL busy;
#end
.m
#implementation NSObject (busyMode)
BOOL _bsy;
-(BOOL)busy{
return _bsy;
}
-(void)setBusy:(BOOL)busy
{
_bsy = busy;
}
#end
as i read along many post, it says that we cannot have instance variables in category. And so above code should not work. But as i tried it out, all was working fine.
Has there been any changes related to category or was it just luck??
As others have pointed out, you didn't add an instance variable, but a global variable which is going to be shared among all of your instances.
Categories cannot add instance variables. However, you can simulate instance variables if you absolutely need them with objc_setAssociatedObject() and objc_getAssociatedObject().
That's because you have defined a single global variable, which isn't an instance variable.
Try and instantiate two instances of this object and you will observe that each instance cannot hold a different value.
You have not added an iVar. You have defined a global variable _bsy and are accessing it in the getter/setter for the property defined by your category.
I have a macro that lets you declare "properties" in categories like this:
#implementation NSObject (AwesomeUtils)
JESynthesize(assign, NSInteger, index, setIndex);
JESynthesize(strong, NSString *, name, setName);
JESynthesize(copy, void(^)(void), completion, setCompletion);
JESynthesize(unsafe_unretained, id, unsafeObject, setUnsafeObject);
JESynthesize(weak, id<UITableViewDelegate>, delegate, setDelegate);
JESynthesize(strong, NSString *, readonlyID, changeReadonlyID);
// …
#end
I say "properties" with quotes because you can use them even without the #property declaration. The macro also works around to support weak.
You can check the implementation here (the header files are at the bottom):
http://nspicks.com/2013/12/15/cleaner-properties-implementation-in-categories/

Property - Implementation of variables in Objective-C

Well ! I got confused about the way of declaring variables & implementing its properties.
The .h File contents
#interface XYZAppDelegate : NSObject <UIApplicationDelegate> {
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet XYZViewController *viewController;
#end
The .m File Contents
#import "XYZAppDelegate.h"
#import "XYZViewController.h"
#implementation XYZAppDelegate
#synthesize window=_window;
#synthesize viewController=_viewController;
My questions/Queries are as follows.
Don't we require to declare variables if we put property ? ( Using property, we can indirectly declare variable - is it like that ? )
What are the additional features other than this ? ( In coding specific )
Why does everybody insist to use _ before each property accessor ? ( Other than security threats ? Has it become coding standard ? Whats the reason behind it? )
You do not have to declare the
variable. It is done automatically,
I believe by #synthesize. One
advantage to declaring it is that the
debugger will automatically list it.
Weigh this against the ugliness of
redundant definition.
Other features: read only properties,
assigned (unretained) values.
The underscore is a convention for
naming member variables that are
differently named than properties and
method variables. Apple's samples
sometimes use this convention and
sometimes do not. I view it as
usually unnecessarily verbose as a
programmer can easily tell the
difference between myVariable and
self.myVariable.
1) Don't we require to declare variables if we put property ? ( Using property, we can indirectly declare variable - is it like that ? )
No. You aren't required to declare variables for the corresponding properties. You are required to use the #synthesize propertyName command which tells the compiler to create those variables for you.
2) Why does everybody insist to use _ before each property accessor ? ( Other than security threats ? Has it become coding standard ? Whats the reason behind it? )
Most people (all?) have been stung by memory management nightmares. Some of these are caused by sloppy/lazy/zero-sleep coding. Using #synthesize propertyName = _propertyName allows the programmer to immediately know that the underscored variable is private to the class, and is unretained. It prevents issues where you specifically allocate or copy an object to store in the property, or accidentally assign an autoreleased object to the ivar.
Consider:
1) An autoreleased object being assigned to an unretained ivar.
#synthesize propertyName;
propertyName = [NSString stringWithFormat:#"I've just made %#", "a boo-boo."];
"propertyName" now references an object that will soon not exist, which will create EXEC_BAD_ACCESS errors down the road (as soon as it's referenced again).
2) A retained object being set to the retained property.
#synthesize propertyName;
self.propertyName = [[NSString alloc] initWithFormat:#"I just created %#", #"a leak"]
Now we've created an NSString object, and set it to the propertyName property, which itself is retaining the variable. Now the object is double retained and won't be properly released.
Both of these issues are easy to combat (even when tired, albeit less so) when you properly name your ivars with an underscore. It's not a fool-proof method, but it makes it considerably easier to manage the retain counts of objects in your head.
(1) No, not with the new 64-bit only features. The variables are declared for you, automatically.
(2) I don't know what you're asking here.
(3) It's just a convention, so that the variable name is different from the accessor name. Makes it clearer which you're dealing with.

Objective-C synthesize property name overriding

I am trying to understand the purpose of the synthesize directive with property name overriding. Say that I have an interface defined as follow:
#interface Dummy ... {
UILabel *_dummyLabel;
}
#property (retain, nonatomic) UILabel *dummyLabel;
And in the implementation file, I have:
#synthesize dummyLabel = _dummyLabel;
From what i understand, "dummyLabel" is just an alias of the instance variable "_dummyLabel". Is there any difference between self._dummyLabel and self.dummyLabel?
Yes. self._dummyLabel is undefined, however _dummyLabel is not.
Dot syntax expands out to simple method invocations, so it's not specific to properties. If you have a method called -(id)someObject, for example in the case of object.someObject, it will be as if you wrote [object someObject];.
self.dummyLabel //works
self._dummyLabel //does not work
dummyLabel //does not work
_dummyLabel //works
[self dummyLabel]; //works
[self _dummyLabel]; //does not work
Your understanding is incorrect. dummyLabel is the name of the property, and is not an alias for the instance variable - the instance variable is only called _dummyLabel. So the following holds for an instance of Dummy called myObject:
[myObject dummyLabel] works
myObject.dummyLabel works
[myObject _dummyLabel] fails
myObject._dummyLabel fails
myObject->dummyLabel fails
myObject->_dummyLabel depends on the visibility of the ivar (#public, #private, #protected)
[myObject valueForKey: #"dummyLabel"] works
[myObject valueForKey: #"_dummyLabel"] depends on the implementation of +accessInstanceVariablesDirectly (i.e. it will work in the default case where +accessInstanceVariablesDirectly returns YES).
The advantage of having another name
for the ivar than for the property is
that you can easily see in the code
when you are accessing one or the
other - Andre K
I'm not able to find a 'comment' button so I'm having to post as an 'answer'.
Just wanted to expand on Andre's comment - by knowing when you are using the synthesized properties vs the vanilla variable, you know (especially in case of setters) when a variable is being retained/copied/released automatically thanks to your nice setter, vs being manipulated by hand.
Of course if you are doing things right, you probably don't need the help of a setter to retain/release objects properly! But there can be other scenarios too where referring to your ivars as self.ivar instead of _ivar can be helpful, such as when you are using custom setters/getters instead of the default synthesized ones. Perhaps every time you modify a property, you also want to store it to NSUserDefaults. So you might have some code like this:
#interface SOUserSettings : NSObject {
BOOL _autoLoginOn;
}
#property (nonatomic, assign) BOOL autoLoginOn;
#end
#implementation SOUserSettings
#synthesize autoLoginOn = _autoLoginOn;
- (void)setAutoLoginOn:(BOOL)newAutoLoginOnValue {
_autoLoginOn = newAutoLoginOnValue;
[[NSUserDefaults standardUserDefaults] setBool:_autoLoginOn forKey:#"UserPrefAutoLoginOn"];
}
#end
Note: This is just illustrative code, there could be a thousand things wrong with it!
So now, in your code, if you have a line that says _autoLoginOn = YES - you know it's not going to be saved to NSUserDefaults, whereas if you use self.autoLoginOn = YES you know exactly what's going to happen.
The difference between _autoLoginOn and self.autoLoginOn is more than just semantic.
I don't see any big advantage of
renaming _dummyLabel to dummyLabel
In some ObjC runtimes you have a hard time making instance variables invisible to users of the class. For them sticking some prefix (or suffix) on your instance variables can make it clear (or more clear) that you don't want anyone messing with your variables. However you don't want that gunk on your public functions. This lets you get it off.
It could also be useful if you need to maintain an old interface with one set of names at the same time as a new set of APIs with a new set of names (setLastname vs. setSurname).
Old post, but I think its important to mention, that it is recommended to access variables via getters and setters (so, with dot notation). Accessing a field directly (_ivar) is strongly recommended only when initializing it.
There is some good Apple's article:
https://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html
Last paragraph:
You should always access the instance variables directly from within
an initialization method because at the time a property is set, the
rest of the object may not yet be completely initialized. Even if you
don’t provide custom accessor methods or know of any side effects from
within your own class, a future subclass may very well override the
behavior.