Should get 20 errors... but get 0... when compiling without declaring an instance variable - iphone

In my iPhone apps I regularly do this in xCode v3.2.3:
Declare a BOOL variable in the *.h file
Use #property in the same *.h file.
Use #sythesize in the matching *.m file.
I accidentally forgot to do #1... but it still complied fine. 0 warnings. 0 errors. 0 analyzer errors.
How can that be? Shouldn't my code to loaded with compiler-errors everywhere that variable is trying to be used?

This is a feature of the new runtime. See this question for more details.

Automatic synthesis of instance variables (ivars) is a feature of the Objective-C 2.0 runtime on OS X and of the new iOS Objective-C runtime. The #synthesize directive will automatically create the necessary ivar at runtime unless you have declared it yourself. This is made possible by Objective-C 2.0's non-fragile ivar support. Thus, there is no error and you should not receive them.
Ultimately, it's a good thing that you don't have to declare ivars in the interface of a class. They are (probably) implementation-specific details which you don't want to have visible as part of the public interface of the class. Note that using class categories you can also automatically synthesize ivars for "private" properties as well.

Related

Usage of Properties in iPhone Programming [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there any reason to declare ivars if you're using properties exclusively in Objective-C?
ObjectiveC ivars or #property
I am new to iPhone programming (and the programming scene altogether). I have tried to study about Properties at various places and found out that they are basically the shortcut to making getter and setter methods for other classes to get access to those objects.
Now, I have seen programmers define the object in the curly braces after the #interface:UIViewController as well as in the properties after that when all the accessing will happen within that class' .m file.
Now, that superfluous (?) piece of code, is it necessary? Is this a standard? Looking forward to some intelligible opinions.
Thank you in advance.
I can interpret your question in a number of ways:
Question: Why do some programmers use properties and instance variables (the variables defined within the curly braces), and others just use properties, and other just use instance variables?
Answer: As you know, #property declarations will, when you #synthesize them, will generate the getters and setters for you. Historically, this is all that it did for you and you had to also manually declare your instance variables. Later, the compiler was improved so that if you didn't have the instance variable defined, that the #synthesize statement would generate that, too. When this was first introduced, common practice was to define both the property and the instance variables, but Apple eventually shifted their guidelines and encouraged programmers to not define instance variables, but let the compiler generate that itself from the #property and #synthesize declarations.
So, in answer to your questions: 1. defining instance variables for your properties is now superfluous; 2. it is no longer necessary; and 3. it is now standard to not explicitly declare instance variables, but rather to let the #synthesize statement do that.
As an aside, the convention on the #synthesize statement is to, with an property called var, to precede the instance variable name with an underscore, thus #synthesize var = _var. This is done to minimize the chance that a programmer might accidentally refer to an ivar when the property was intended (or vice versa). To further illustrate that this is the preferred standard, starting in Xcode 4.4, even the #synthesize statement is optional (thus, define the #property, but no ivar, and no #synthesize) and it will declare and ivar the same name as your property, except with a leading underscore.
Question: Why do some programmers define some of their properties and instance variables in the .m file? Why do other programmers declare some of their instance variables and properties in the .h file when they're only being used within the class's own .m file.
Answer: Those instance variables and properties defined within the .m file (in what is called a class extension) are just a convenient way of defining those ivars/properties that are not advertised to the world. In this convention, your .h file becomes just your public interface (what properties and methods can be invoked from elsewhere) and everything else goes in the .m file. It's a nice way to keep your interfaces a little cleaner so when you go to use your class at some future date, you can just look at the .h file and not get too lost in the details of the class's implementation details.
In the past, before class extensions became prevalent, we defined all of our instance variables and properties in the .h file, even if they were private and used only within the class's own .m file. Thus, you'll still see some code that does this.
So, in answer to your questions, 1. it's not superfluous to use class extensions (unless your class extension is empty, but even then I tend to keep it so I can see that there are no private ivars/properties); 2. the use of class extensions is not necessary; but 3. the use of class extensions for private properties/variables that are used only within the class itself is an emerging standard and probably does represent best practice.

When to use #property? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why should I use #properties?
When to use properties in objective C?
I have been programming in objective-c for a little over a year now, and I always felt like it was a convention to use #property and #synthesize. But what purpose do they really serve ? Are they solely there to be communicated between classes ? So, for instance, if I use an NSMutableDictionary only in the scope of the class where it was declared, an omission is O.K. ?
Another question:
If I set the property of an NSMutableDictionary, it is retained, right ? So, in my class I don't have to call alloc() and init(), do I ?
What are the rules to use properties ?
But what purpose do they really serve?
Access control to iVars and abstraction between representation and underlying data.
Are they solely there to be communicated between classes?
No, they are for when you want to control access to iVars instead of accessing them directly or when you could in the future change underlying data structures but wish to keep the current representation.
So, for instance, if I use an NSMutableDictionary only in the scope of the class where it was declared, an omission is O.K.?
It depends. Do you want to have controlled access to the iVar? Would it be possible for your code to change so the dictionary is fetched and not a direct iVar. Usually, the answer is yes.
If I set the property of an NSMutableDictionary, it is retained, right?
Depends on how you declare the property.
So, in my class I don't have to call alloc() and init(), do I?
You have sloppy wording here. I think you are asking if you still need to construct an instance of a property. Yes, you will need to construct an instance of a property in some way. There are lots of ways of doing this.
NOTE: the convention for talking about methods is use their signature. Instead of alloc(), you would use -alloc.
What are the rules to use properties?
This you will need to read the doc for.
Like in another languages, when we want to make our variable global or public we use public access modifier. In objective c when we want access our another class variable in other class, we use #property and #synthesize them. Basically #synthesize is way by which compiler create a setter and getter methods for that variable. You can manually create them but not use #synthesize.
By creating object of that class you can access your property variable in other class.
By using retain, you clear that is take place memory and not exist until that container class not goes dispose or released.
Properties simply make your life easier.
Nowadays use properties as much as you can in terms of memory management, code-style and timesaving.
What do #propertys do?
They can create getter and setter methods (depends on given parameters).
Normally you declare instance variables in the header file (like in c++).
Now you simply let that be and instead of that declare the properties you want for instance variables.
Properties can get multiple arguments.
For normal objective-c objects, where you need a pointer (*) you would write.
#property (nonatomic,retain,...)
When you #synthesize it it creates a getter and a setter.
The setter automatically does stuff like releasing your old object, that your variable hold and retaining the new one.
So you don't have to do that manually (which should be quite often the case). Thats important.
You also can give it arguments (readonly,readwrite) to decide if to set a setter or not.
You can even declare a #property in the header file readonly and override that in your implementation file with a extension (a category with no name).
To dive deeper into this, read the apple developer manuals, which are quite effective.
Hope that helps a bit.
Shure it is the tip of the iceberg, but it's mostly everything you need.

How can I avoid redundancy while declaring new class attributes in Objective-C?

In my code, every time I need a new object attribute for my class, I typically copy/paste its name in 4 different places!
The declaration in the header file (NSObject * myObject;)
The #property() line
The #synthesize() line in the implementation
Releasing it under dealloc: (only for objects of course)
I do this because it works, not because I completely understand what's going on. I do know that the declaration in the header file allows other classes to see its attributes, the property specifier determines how its getter/setter methods will be constructed. And the synthesize line actually builds those getter/setter methods. I also know that primitive types should use (nonatomic,assign) instead of (nonatomic,retain), but I have no clue when I should omit the nonatomic.
What can I do to avoid redundancy in my code. If I change or add a variable in my class I have to check 4 different places, and it gets old really fast. Are there any key strokes to make this process faster? Are there lines of code I can simplify or combine to obtain the same result?
Accessorizer will automate a lot of this for you.
In the latest version of Clang (Ships with XCode 4, not in XCode 3 yet) you get default #synthesize as well as default ivar creation. The default ivar creation already works, but not on the simulator. With both of these features all you need to do is add the #property line and deal with the memory management in dealloc
As far as nonatomic vs atomic. atomic is the default, and what happens when you leave off the nonatomic annotation. Atomic guarantees that the value is completely set before allowing anything to access it, nonatomic doesn't. Atomic is only useful in threading situations, and is slightly slower in singlethreaded applications.
It's important to understand what each of those lines of code does. They are not all the same and they are not necessarily redundant. One thing that will help is to use the correct terminology — for example, with NSObject *myObject; you're probably referring to an instance variable declaration.
First and foremost, a #property declaration in an #interface lets you say that instances of a class expose a piece of state. It doesn't say much about the implementation of that state, only that it's exposed by instances of your class and the API contract (memory management, atomicity, methods) for the state.
The #synthesize directive tells the compiler to create or use a specific instance variable as storage for a declared #property. This does not need to be how you provide storage for a property. For example, Core Data provides its own storage for modeled properties, so you use #dynamic for those instead. You also don't need to use an instance variable with the same name as your #property — to extend your example above, you might name your instance variable myObject_ while naming your property object and that's perfectly fine.
Finally, you send the instance variable -release in -dealloc — for an object-type property marked retain or copy — because you've said you'll manage its memory. You're not releasing the property, you're releasing the storage. If you implemented the storage some other way, you'd clean it up some other way.

CoreDataGeneratedAccessors not generating automatic selectors

I am currently working on an App which uses core data. I tried specifying CoreDataGeneratedAccessors in the interace itself, but accessors like setName do not seem to be automatically generated.
Is this something wrong with my XCODE configuartion?
Thanks,
Jith.
The generation of accessors by properties is a function of the language version and it is nearly impossible to change the language version in Xcode. In fact, I've never seen anyone with that problem.
You're most likely missing the #dynamic directive for the property in the implementation (.m) file. You need to have something like:
#implementation MyManagedObject
#dynamic propertyName;
... to get the accessors for managed objects.

Objective-C changes between OS 2.2.1 and OS 3?

When I tried compiling my app for OS 3 I encountered an the following error:
error: type of accessor does not match the type of property
The error was for a property I tried to access that is defined as follows:
NSMutableArray *myArray
#property (readonly,nonatomic) NSArray* myArray;
the property is #synthesized in the implementation file.
This worked just fine in OS 2.2.1 but doesn't is OS 3.0
Writing the getter method myself solved the problem.
Is anyone aware of changes to objective-c between OS 2.2.1 and 3.0?
Is there any documentation for these changes?
The API changes document doesn't appear to contain anything about this issue.
EDIT
the error occurs when you try to access the property e.g.
NSArray *anArray = myClass.myArray;
As I mentioned above I found a workaround for this: writing the getter method myself, however what I'm really after is some kind of documentation from apple explaining this change and any other changes that are not API related.
Thanks for your help
This is a compiler bug.
Though you didn't specify it completely, I expect your code looks like this:
#interface Foo : NSObject {
NSMutableArray *objects;
}
#property (readonly, copy) NSArray *objects;
#end
#implementation Foo
#synthesize objects;
#end
The compiler is, unfortunately, confused between the declaration of the objects property and the declaration of the objects instance variable. Remember that properties and instance variables are different things in Objective-C; a property can be backed by an instance variable, but it's really part of the public interface of a class.
You can work around this by changing your code to clearly separate the definition of the instance variable from the definition of the property, for example by prefixing the name of the instance variable:
#interface Foo : NSObject {
NSMutableArray *_objects;
}
#property (readonly, copy) NSArray *objects;
#end
#implementation Foo
#synthesize objects = _objects;
#end
This way the compiler doesn't get confused about the property versus the instance variable in expressions like self.objects (which it shouldn't anyway, but apparently does).
Just to head off the inevitable response: Apple does not reserve the underbar prefix for instance variables. It's reserved for methods. Regardless, if you dislike the underbar, feel free to use another prefix.
edit: Original answer removed after peer review found it lacking. Please read Chris Hanson's comments on the matter. I'm leaving the rest here because I think it is still valid.
Note that even if you declare the property type to be NSArray, the object returned is still an NSMutableArray, and the mutable methods are defined for it. Declaring the property in this way does not prevent someone from accidentally mutating the array.
If you want to be sure that the returned array is not mutable, you could declare the property as in your original example, and then roll your own accessor:
- (NSArray *)myArray { return [NSArray arrayWithArray:myArray]; }
Note that this would return an unretained NSArray. It would be up to the caller to take ownership of the object if it needed to persist.
You are seeing errors because XCode is now issuing warnings and errors for things it did not previously...
I would argue that it should be at most a warning to do what you are doing, I understand your attempt to present the array as immutable to the outside world but have it mutable inside the class. You may want to consider a different accessor with a different name, built to return the mutable array specifically.
It is still Objective-C 2.0; the compiler is just maybe a little updated with considering this kind of type changing an error. It pretty much should be an error. At least it should warn you that you likely don't mean what you wrote. Then you could cast stuff to make it not warn you, which you can't do with the #synthesize statement.
I just exactly pasted your code and a synthesize statement into my controller and I got no errors or warnings about it. It built fine. Now I set the base SDK to "Simulator 3.0", and the build to "Simulator 3.0 Debug". This project had started in the 2.2.1 SDK and I just installed the 3.0 SDK yesterday; Xcode is version 3.1.3.
Update: Oh I see that actually trying to set the property is where you get the error you mentioned.
self.myArray = [NSArray arrayWithObject:#"foo"];
Clearly you cannot #synthesize this behavior and must write your own accessors.
- (NSArray*)myArray {
return [NSArray arrayWithArray:myArray];
}
- (void)setMyArray:(NSArray*) pMyArray {
myArray = [NSMutableArray arrayWithArray:pMyArray];
}
Filling in these accessors, did not make the message go away, so I had to change the access to:
[self setMyArray:[NSArray arrayWithObject:#"foo"]];
Using the above syntax without custom accessors also did not work.
PS Wow, is anyone else annoyed that you can neither copy message bubbles, or the text in the build results window?
So this is really to do with the #synthesize call that is not happy about exposing a NSMutableArray as an NSArray - why not just implement the getMethod.
Actually thinking about it it must be the set method that is not happy - you wouldn't be able to set an NSArray into an NSMutableArray.
Your questions were:
Is anyone aware of changes to objective-c between OS 2.2.1 and 3.0?
Is there any documentation for these changes?
The definitive answers are:
1) There were no intentional changes to the language specification, but the compiler and other developer tools changed. Chris and his coworkers are the experts on those changes.
2) Probably not, because any changes were unintentional or made to better match behavior with the documentation.
You shouldn't be so quick to dismiss Chris' answer as "a guess." Chris works on Apple's developer tools. You might get another answer you like more, but you won't be getting a more expert answer.