What is the difference between these two?
#property (nonatomic, retain)
#property (nonatomic, copy)
What is the other type like this?
http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW27
Using retain is equivalent to this method:
- (void)setMyObject:(id)object {
myObject = [object retain];
}
Using copy is like this:
- (void)setMyObject:(id)object {
myObject = [object copy];
}
The main difference is that there are now two copies of the same object. Now, if you change an instance variable in your class (such as changing #"A" to #"B"), the original object will stay intact (it will still be #"A").
As a general rule, use:
#property(nonatomic, copy)
..for NSString properties and this for all other object properties:
#property(nonatomic, retain)
For attributes whose type is an immutable value class that conforms to the NSCopying protocol, you almost always should specify **
copy
** in your #property declaration. Specifying **
retain
** is something you almost never want in such a situation.
Since in almost all cases you want to prevent mutating an object's attributes behind its back, you should mark the properties representing them copy. (And if you write the setter yourself instead of using #synthesize you should remember to actually use copy instead of retain in it.)
Related
I use Core Data and have an object ExerciseForRoutine. I'm currently manually creating it and then settings it's attributes, which seems to waste code. Is there any way I can create a custom init method to handle this in one line (I know how to do around alloc/init, but core data has a different init method..)
Current Code:
ExerciseForRoutine *exerciseForRoutine = (ExerciseForRoutine *)[NSEntityDescription insertNewObjectForEntityForName:#"ExerciseForRoutine" inManagedObjectContext:managedObjectContext];
exerciseForRoutine.name = self.selectedExercise;
exerciseForRoutine.timeStamp = date;
exerciseForRoutine.muscleGroup = self.muscleName;
exerciseForRoutine.musclePicture = self.muscleURL;
ExerciseForRoutine Class
#class Routine;
#interface ExerciseForRoutine : NSManagedObject {
#private
}
#property (nonatomic, strong) NSDate * timeStamp;
#property (nonatomic, strong) NSString * name;
#property (nonatomic, strong) NSString * muscleGroup;
#property (nonatomic, strong) NSString * musclePicture;
#property (nonatomic, strong) Routine * exerciseToRoutine;
#end
#implementation ExerciseForRoutine
#dynamic timeStamp;
#dynamic name;
#dynamic muscleGroup;
#dynamic musclePicture;
#dynamic exerciseToRoutine;
I did this using awakeFromInsert and awakeFromFetch.
From Apple's documentation:
In a typical Cocoa class, you usually override the designated initializer (often the init method). In a subclass of NSManagedObject, there are three different ways you can customize initialization —by overriding initWithEntity:insertIntoManagedObjectContext:, awakeFromInsert, or awakeFromFetch. You should not override init. You are discouraged from overriding initWithEntity:insertIntoManagedObjectContext: as state changes made in this method may not be properly integrated with undo and redo.
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/Articles/cdManagedObjects.html
The classes which Xcode creates for handling core data objects should not be overridden, instead what you could do is create your own custom class which inherits from NSObject and write your methods to handle the managed object their.
Sol: You can do this with the help of the parameterized init method
Then it would look something like this
CoreDataHelperClass *someobj = [[CoreDataHelperClass alloc]initWithname:#"name" andTimeStamp:#"Time" andMuscleGroup:#"musclegroup" andPicture:UIImagePNGRepresentation(someimageObj)];
To do the above you need to add your own init method in the CoreDataHelperClass class like this
.h part of CoreDataHelperClass
- (id)initWithName:(NSString*)name andTimeStamp:(NSString*)timeStamp andMuscleGroup:(NSString*)group andPicture:(NSData*)imageData;
.m part of CoreDataHelperClass
- (id)initWithName:(NSString*)name andTimeStamp:(NSString*)timeStamp andMuscleGroup:(NSString*)group andPicture:(NSData*)imageData
{
//you assignment code to the core data attributes goes here
ExerciseForRoutine *obj = [[ExerciseForRoutine alloc]init];
obj.name = name;
obj.timestamp = timeStamp;
//and so on
return self;
}
Anyways what you could also do is pass a dictionary with the keyvalue pair get the values in your custom class or you may also pass an NSMutableArray like what ever suits your business model both will work.
You can get the values of Dictionary or Array inside your CoreDataHelperClass and assign those values to your attribute.
Hope i have got your query right if not then kindly mention the error part via comments
To add to #Radix's answer, you should consider using mogenerator because it'll do much of that subclassing business for you.
http://rentzsch.github.io/mogenerator/
See here for a guide to set it up and have it running on XCode 5.
There's a small caveat to watch out for though: if you get an assertion failure that reads:
-[MOGeneratorApp setModel:] blah blah blah
Then you should point mogenerator to the .xcdatamodel file inside of the .xcdatamodeld package in your Run Script Phase, like so:
mogenerator -m Model.xcdatamodeld/Model.xcdatamodel -O Project/Model --template-var arc=true
Where Project is the name of your project and Model is the name of your model.
See https://github.com/rentzsch/mogenerator/issues/169.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
NSString retainCount is 2147483647
Let say i have an class named as MyTestClass.h.
There are three NSString variables which are initialized different ways
Class structure is look like
#interface MyTestClass : NSObject {
NSString *testString1;
NSString *testString2;
NSString *testString3;
}
#property (nonatomic, retain) NSString *testString1;
#property (nonatomic, retain) NSString *testString2;
#property (nonatomic, retain) NSString *testString3;
#end
MyTestClass.m
#implementation MyTestClass
#synthesize testString1, testString2, testString3;
-(id) init{
self.testString1 = #"";
[self setTestString2:#""];
testString3 = #"";
}
Now i am planning to create an object of MyTestClass
MyTestClass *obj = [[MyTestClass alloc] init];
I think after this code line execution testString1, testString2 and testString3 retainCounts will be 1.
Am i correct my friends?
may i know that what will happened if i release testString3 ?
Any help on this is appreciated.
Thanks
Since you are using literal strings in this example retainCount is of no importance (not even as a delta) since those string objects aren't actually ever going to be dealloc'd.
However, if you were assigning a runtime allocated string to each of your properties, the first two would be retained, the third would not. Since your properties are declared as retain and you're using dot syntax in one and the "setProperty" syntax in the other, the same setter is executed and the object passed to that setter is retained. The third example you're simply setting the backing ivar for the property to the value on the right and not affecting it's ownership.
It's worth noting, retainCount is only ever useful as a delta and shouldn't be thought of as an explicit number. You should never explicitly check the value of retainCount, since it's absolute value is unpredictable and of no use. You seem to understand this in your question, but it's worth restating whenever dealing with retainCount to make sure all involved understand it.
Sorry for the simple question.
When I see a definition of a property inside the h file, but outside of the class #interface scope, what does it mean ?
#property (nonatomic, readonly) RMMapContents *mapContents;
Here is the code:
#class RootViewController;
#class RMMapContents;
#interface MapTestbedAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
//MAIN VIEW
//==============
RootViewController *rootViewController;
// NETWORK DATA
// =============
NSMutableArray *photoTitles; // Titles of images
NSMutableArray *photoSmallImageData; // Image data (thumbnail)
NSMutableArray *photoURLsLargeImage; // URL to larger image
NSMutableData *receivedData;
NSURLConnection *theConnection;
NSURLRequest *request;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet RootViewController *rootViewController;
#property (nonatomic, readonly) RMMapContents *mapContents;
#end
Inside a function I see this line:
- (void)foo:(xyz *)abc{
..
RMMapContents *mapContents = [self mapContents];
..
}
So, taking it from C++, the mapContents seem like it is not a global scope var (after all, that's why they call them properties, right?), but isn't defining the same name again inside the function weird a bit?
I hope someone can clarify a little here.
Thanks!
The scope of the #interface block extends upto the #end keyword and is not restricted to the braces {}.
So the #property declaration lies very much inside the scope of the #interface and like cli_hlt rightly answered, it acts like a substitute to setter and getter methods for the mapContents property.
so a property named mapContents, would have setters and getters which look like this :
- (void)setMapContents; //setter
- (RMMapContents *)mapContents; //getter
and would can be accessed from within the class using these methods:
[self setMapContents:newContents];
AND
RMMapContents *contents = [self mapContents];
Well, a property is not just a variable. A property is a variable plus its setter and getter methods. A property is usually said to be backed by a variable, which usually(but not always) has the same name as the property itself.
So there are basically three scenarios:
The developer has redefined the backing variable, look for something like:#synthesize mapContents=mapContents_, at the beginning of the implementation -> no problem here.
The compiler defined the variable to be something you don't now but not equal to mapContents - > no problem.
The property backing variable is indeed called "mapContents", so then the local definition hides the global definition (look for a compiler warning here). But by calling [self mapContents] you will not access the global variable but call the getter, which in turn will access the class variable (because then the local mapContents is out of scope)
Hope this helps.
global var mapContents is readonly,in foo function , create a new pointer,then you can change the value of inner var.
Look for a method in your class with a name mapContents that will return a initialization to your RMMapContents class.
Basically this line RMMapContents *mapContents = [self mapContents]; says that initializing an instance of RMMapContents called mapContens using the method mapContents.
I was going through the AVCam project from WWDC and I'm curious about the following code. I thought you were supposed to declare an object, then #property (nonatomic,retain), then synthesize.
The Demo code does it a little differently, I'll post some code (just a sample), anyone know what this does and when you should use it? Can anyone explain its significance and when to use it?
#interface AVCamCaptureManager : NSObject {
#private
// Capture Session
AVCaptureSession *_session;
AVCaptureVideoOrientation _orientation;
// Identifiers for connect/disconnect notifications
id _deviceConnectedObserver;
id _deviceDisconnectedObserver;
}
#property (nonatomic,readonly,retain) AVCaptureSession *session;
#property (nonatomic,assign) AVCaptureVideoOrientation orientation;
#property (nonatomic,readonly,retain) AVCaptureAudioChannel *audioChannel;
#property (nonatomic,assign) NSString *sessionPreset;
in the implementation file:
#interface AVCamCaptureManager ()
#property (nonatomic,retain) AVCaptureSession *session;
#property (nonatomic,retain) AVCaptureDeviceInput *videoInput;
#property (nonatomic,retain) AVCaptureDeviceInput *audioInput;
#end
#implementation AVCamCaptureManager
#synthesize session = _session;
#synthesize orientation = _orientation;
#dynamic audioChannel;
#dynamic sessionPreset;
#dynamic focusMode;
- (id) init
{
#property (nonatomic,readonly,retain) AVCaptureSession *session;
This is a property that is readonly externally. Internally, it will have a setter that retains the new value.
#property (nonatomic,assign) AVCaptureVideoOrientation orientation;
This is a property that does a simple assignment to store the new value (since you can't -copy or -retain primitives).
#property (nonatomic,readonly,retain) AVCaptureAudioChannel *audioChannel;
This is a property that is readonly externally. Internally, it will have a setter that retains the new value.
#property (nonatomic,assign) NSString *sessionPreset;
This is a property that does a simple assignment to store the new string value. This is normally not a good idea, unless you're only allowing pre-defined constants for the presets. When dealing with NSString properties, you generally want them to be copy unless you have a good reason against it.
In the implementation file:
#property (nonatomic,retain) AVCaptureSession *session;
#property (nonatomic,retain) AVCaptureDeviceInput *videoInput;
#property (nonatomic,retain) AVCaptureDeviceInput *audioInput;
These are used in conjunction with the properties declared in the header, except now it's readwrite. By declaring the version in the header as readonly, anyone using the class will not have access to the setSession: method. We re-declare this property internally so that we can have access to the setter (and the setter retains the new value). Also, if the property is not present in the header, the user won't know it exists, but we'll still be able to use it internally.
#synthesize session = _session;
#synthesize orientation = _orientation;
This means you want the compiler to generate the appropriate setters and getters for the session and orientation properties, and that you want those properties to store their values in the _session and _orientation instance variables, respectively.
#dynamic audioChannel;
#dynamic sessionPreset;
#dynamic focusMode;
This means that the implementations for the setters and getters will be provided at runtime. You usually don't use #dynamic properties yourself, other than the ones provided by the Core Data framework.
In this code, the session property is defined as readonly outside of the class and readwrite inside the class. By overriding the session property in an unnamed category before synthesizing it, a set accessor will also be synthesized, but the header file says it is readonly so other classes don't know about the set accessor. The category also defines two new properties which are not visible to other classes at all.
The retain and assign keywords tell the compiler how the accessor methods should work. Retain means that the set accessor should retain the value of the property, and the assign keyword tells it to set the property without retaining it. There is also copy, which copies the value and is often used to make sure a mutable value isn't set. The default is assign, but the compiler will issue a warning if nothing is specified for an object property.
Can you explain what you're confused about here? My only guess is you are confused about audioChannel and sessionPreset, as they have no ivars and are declared #dynamic (there's also focusMode, but I don't even see a #property declaration for that in the code you pasted).
In any case, I expect that if you read the rest of the code you'll find that there are getters for -audioChannel and -sessionPreset that have been written, as well as a setter for -setSessionPreset:. Assuming that's the case, then the #dynamic declarations are completely unnecessary. #dynamic is only necessary to tell the compiler that the methods will exist at run-time; if they exist at compile-time then you don't need any directive whatsoever.
What do #synthesize and #property do in Xcode? Please provide an explanation in really simple terms?
You asked for simple terms:
#property declares a property in your
class header
#property (nonatomic, retain) NSString *myString;
#synthesize creates your setter and
getter for your property (accessor
methods)
Without synthesize you have to write
your own setter and getter
implemention, like getMyString or
setMyString (capitalize the first
character of your property)
Sam: Just an advice: http://www.cocoadevcentral.com/d/learn_objectivec/ is a pretty solid resource to learn about basics like properties.
Good Luck!
Properties and synthesized accessors are new features in Objective-C 2.0.
When you declare a #property you declare somewhat an instance var. Then you #synthesize accessor methods (i.e. getter and setter) for that property.
There are also #dynamic accessors if you're interested.
You should really do your homework on this. Apple has nifty pdf for that.
Think of all objective-c magic as just a "smarter macro", like a "smarter #define statement"
#property if you notice is always in the h file,
#synthesize is always in the m file.
So in the background
#property (whatever) NSString *myString;
becomes a declaration of 2 methods and a private variable;
void set_myString:(NSString *) str;
(NSString*) get_myString;
declarations in the header file
to make them do something their implementation is added into m file when you type in
#synthesize myString;
which becomes something like
void set_myString:(NSString *)str
{
myString = str;
}
(NSString *) get_myString
{
return (myString);
}
But it's smarter than this
depending on if you say "retain" "strong" or "weak"
it will either just return the pointer to the myString or it will copy the myString into a new object
So all of this is done automatically by a compiler just by reading your declarations.
Which is quite useful and saves a lot of time
By default all our variables are Private so we can't acess out of the class.
if we want to use our instance variable in out of the class.
When you declare a #property you declare somewhat an instance var. Then you #synthesize accessor methods (i.e. getter and setter) for that property.
There are also #dynamic accessors if you're interested.
it simply sets the property's setter variable name in it's own class.
For example lets say I have this: #property (nonatomic, copy) NSArray* viewControllers;
Well if i want to access the setter _viewController i wouldn't set a synthesize variable.
but if i want to access the viewController variable by the name viewController instead of _viewController, I would do #synthesize viewController;.
If I wanted to use it as a completely different name I could do this #synthesize viewControllers = viewControlololer; but that's only setter. As you will notice [self viewControllers] only works and not [self viewControlololer];
So I don't understant why everyone writes sets the "setter and getter" of a property. It doesn't change the getter variable at all... unless that means [self viewController] is aware of viewControlololer (obviously).
Actually properties are synthesized, either implicitly or explicitly. Properties are implicitly synthesized. So there's no need to use synthesized unless you wanna change the name of the variable to something different than _property_name.
There are other use cases, for example if you don't want an instance variable to back your property.
Properties are explicitly synthesized by using the #synthesized directive.
(Answer extracted from the Big Nerd Ranch guide)