Without automatic reference counting you often write code like this, when adding a new class:
assuming the classname is "Foo"
+ (id) foo
{
return [[[self alloc] init] autorelease];
}
- (id) init
{
self = [super init];
// do some initialization here
return self;
}
Well, how are you supposed, to write this for arc?
Just like the code below?
+ (id) foo
{
return [[self alloc] init];
}
- (id) init
{
self = [super init];
// do some initialization here
return self;
}
Yes. Are you expecting something different?
Related
I'm trying to initiate my ivar like this:
Declared like this in h-file
#interface MyClass: {
UITextView *_myTextView;
}
then created like this in the m-file
- (id)init {
self = [super init];
if(self) {
[self initTextView:_myTextView];
}
return self;
}
- (void)initTextView:(UITextView *)textView {
textView = [[UITextView alloc] init];
...
}
_myTextView will still be nil afterwards. Why is that and what should I do it to make it work? I've got ARC enabled.
[EDIT]
This works. Thanks all!
- (id)init {
self = [super init];
if (self) {
_textView1 = [self createTextView];
_textView2 = [self createTextView];
_textView3 = [self createTextView];
}
return self;
}
- (UITextView *)createTextView {
UITextView *textView = [[UITextView alloc] init];
...
return textView;
}
You need to always refer to instance variables using:
self.textView = [[UITextView alloc] init];
Also use a name other than initTextView as methods starting with init have special meaning in Objective-C.
If you want to use the same code to initialize multiple text view controls, then use code like this:
- (UITextView *)createTextView
{
UITextView *textView = [[UITextView alloc] init];
textView.something = whatever;
...
return textView;
}
And then use it like this:
- (id)init {
self = [super init];
if(self)
{
self.textView1 = [self createTextView];
self.textView2 = [self createTextView];
...
self.textViewN = [self createTextView];
}
}
In [self initTextView:_myTextView]; you pass the current value of _myTextView (which is nil) to your initTextView: method. To set the instance variable, you need a pointer to a pointer.
- (id)init {
self = [super init];
if (self) {
[self setupTextView:&_myTextView];
}
return self;
}
- (void)setupTextView:(UITextView * __strong *)textView {
*textView = [[UITextView alloc] init];
...
}
I also renamed the initTextView: method to setupTextView, as methods starting with init are expected to behave like other init methods in ARC.
- (id)init {
self = [super init];
if(self) {
[self initTextView];
}
}
- (void)initTextView{
_myTextView = [[UITextView alloc] init];
...
}
if you want to call initTextView for several text views , you can code like this :
- (id)init {
self = [super init];
if(self) {
_myTextView = [[UITextView alloc] init];
[self initTextView:_myTextView];
}
}
- (void)initTextView:(UITextView *)textView{
//setup the textView
...
}
I have been reading about an objective-c singleton example from http://getsetgames.com/2009/08/30/the-objective-c-singleton/.
The .m code looks like
+(MySingleton*)sharedMySingleton{
#synchronized([MySingleton class])
{if (!_sharedMySingleton)
if(!_sharedMySingleton)
return _shareMySingleton;
}
....
-(id)init{
self = [super init];
if(self != nil){}
return self;
}
....
Thanks for your example, but I have a confused place, in your code, I am wondering in which place the static MySingleton* _sharedMySingleton is initialized. for example if we would have to have some implementation like
-(id)init{
self = [super init];
if(self != nil){
_sharedMySingleton = self
}
return self;
}
You miscopied a part of the code from the link you posted by mistake.
#implementation MySingleton
static MySingleton* _sharedMySingleton = nil;
+(MySingleton*)sharedMySingleton
{
#synchronized([MySingleton class])
{
if (!_sharedMySingleton)
[[self alloc] init];
return _sharedMySingleton;
}
return nil;
}
+(id)alloc
{
#synchronized([MySingleton class])
{
NSAssert(_sharedMySingleton == nil, #"Attempted to allocate a second instance of a singleton.");
_sharedMySingleton = [super alloc];
return _sharedMySingleton;
}
return nil;
}
-(id)init {
self = [super init];
if (self != nil) {
// initialize stuff here
}
return self;
}
-(void)sayHello {
NSLog(#"Hello World!");
}
#end
looking at the code from the post you are asking about it actually makes sense.
What he is doing in the static method +(MySingleton*)sharedMySingleton is that he is checking if the _sharedMySingletonobject has a value he is returning it, if not it gets initialized.
The alloc method is the one setting the singleton object, its not being set in the initializer. technically its the same, since its going to be point on the same object that will be initialized a moment after.
I hope that clarifies your confusion.
you can use macro from http://code.google.com/p/google-toolbox-for-mac/source/browse/trunk/Foundation/GTMObjectSingleton.h it is vvveeerryyy easy to use
in implementation file (m)
GTMOBJECT_SINGLETON_BOILERPLATE(ClassName, sharedInstance)
and header file
+ (ClassName *) sharedInstance;
I am new to Objective-C and I am confused about this retain-release thing. Are parameters retained automatically? Do I need to release them?
Here is my code. Did I do the retain-release thing (and everything else) correctly?
#import "ACStringTokenizer.h"
#implementation ACStringTokenizer
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
- (id)initWithStr:(NSString *)theString
{
self = [super init];
if (self) {
string = [theString retain];
delimiters = #" ";
doesReturnDelims = NO;
}
return self;
}
- (id)initWithStr:(NSString *)theString andDelims:(NSString *)theDelimiters
{
self = [super init];
if (self) {
string = [theString retain];
delimiters = [theDelimiters retain];
doesReturnDelims = NO;
}
return self;
}
- (id)initWithStr:(NSString *)theString andDelims:(NSString *)theDelimiters andDoesReturnDelims:(BOOL)returnDelims
{
self = [super init];
if (self) {
string = [theString retain];
delimiters = [theDelimiters retain];
doesReturnDelims = returnDelims;
}
return self;
}
- (int)countTokens
{
return numberOfTokens;
}
- (BOOL)hasMoreTokens
{
return ![queue isEmpty];
}
- (NSString *)nextToken
{
return [queue remove];
}
- (void)dealloc
{
[string release];
[delimiters release];
[queue release];
[super dealloc];
}
#end
Thanks in advance.
P.S. How do I make init with no parameters invalid?
This might be better suited to http://codereview.stackexchange.com?
Anyway, a few points:
You should read up on the concept of Designated Initializer. In your case you'd probably make initWithStr:andDelims:andDoesReturnDelims: the designated initializer. Only this initializer may call [super init]. All other initializers call [self initWithStr:andDelims:andDoesReturnDelims:] instead of [super init].
There are some more elaborate ways to make init invalid, but if you want to disable it I'd simply make it return nil. However, I don't really see a reason why you'd want to do this in this particular case.
The retains in your init methods and the dealloc method seem to be alright. Method parameters are valid until the end of the method, if you want to keep them beyond that, e.g. in instance variables, you need to retain them (which you seem to have done correctly).
However, there's a whole lot of code omitted in your example so obviously I'm only commenting on what you've posted.
A parameter variable is not retained automatically, you only get the object by reference. To keep them you have to retain them, as you did. For me it looks perfectly fine what you did there.
If you have an object with a property which has a retain setter, which of these is best practice?
1
-(id)init {
if((self = [super init])) {
self->_retainingProperty = [[NSObject alloc] init];
}
return self;
}
2
-(id)init {
if((self = [super init])) {
self.retainingProperty = [[NSObject alloc] init];
[self.retainingProperty release];
}
return self;
}
3
-(id)init {
if((self = [super init])) {
NSObject *obj = [[NSObject alloc] init];
self.retainingProperty = obj;
[obj release];
}
return self;
}
All of these would be coupled with a release in dealloc
Perhaps there is another way I've missed.
I generally just do:
- (id ) init
{
self = [super init];
if ( self )
{
retainingProperty = [[NSObject alloc] init];
}
return self;
}
I would not suggest #2 or #3, unless you are aware they might invoke KVO stuff that you do not intend.
All of the above are fine and broadly equivalent. You can also access the member variable using just its name:
-(id)init {
if((self = [super init])) {
_retainingProperty = [[NSObject alloc] init];
}
return self;
}
Property setters are really just convenience methods to ensure the retain/release dance is done correctly, so if you are doing things correctly you can do without them.
If you've added some custom logic to the setter method, you may want to ensure it's called by always using the property setter syntax. Or alternatively, you may want to deliberately sidestep that logic in some instances, and therefore avoid using it some of the time. It's up to you - whatever works for your use case.
At least two other ways immediately spring to mind. There's direct ivar access:
- (id) init
{
if ( self = [super init] )
{
_retainingProperty = [[NSObject alloc] init];
}
return self;
}
Or you could use the autorelease pool:
- (id) init
{
if ( self = [super init] )
{
self._retainingProperty = [[[NSObject alloc] init] autorelease];
}
return self;
}
Depending on the class of the property, there may also be convenience methods equivalent to the latter.
Personally, I would pretty much always go with the direct ivar access. It is usually considered bad form to call property accessors in init, because they may have side effects that you wouldn't want to happen while the object is incompletely initialised.
Similar considerations apply in dealloc, btw: it's better to release your ivars directly rather than using the property accessors.
If I create a custom initWith for an object do I essentially include the code I would add should I want to override init?
-(id) init {
self = [super init];
if (self) {
NSLog(#"_init: %#", self);
}
return(self);
}
e.g.
-(id) initWithX:(int) inPosX andY:(int) inPosY {
self = [super init];
if(self) {
NSLog(#"_init: %#", self);
posX = inPosX;
posY = inPosY;
}
return(self);
}
gary
You can create one designated initializer that accepts all parameters that you want to make available in initialization.
Then you call from your other -(id)init your designated initializer with proper parameters.
Only the designated initializer will initialize super class [super init].
Example:
- (id)init
{
return [self initWithX:defaultX andY:defaultY];
}
- (id)initWithPosition:(NSPoint)position
{
return [self initWithX:position.x andY:position.y];
}
- (id)initWithX:(int)inPosX andY:(int)inPosY
{
self = [super init];
if(self) {
NSLog(#"_init: %#", self);
posX = inPosX;
posY = inPosY;
}
return self;
}
The designated initializer is -(id)initWithX:andY: and you call it from other initializers.
In case you want to extend this class you call your designated initializer from subclass.
I'd suggest creating one main initializer that handles most of the work. You can then create any number of other initializers that all call this main one. The advantage of this is if you want to change the initialization process, you'll only have to change one spot. It might look like this:
-(id) initWithX:(float)x {
if (self = [super init]) {
/* do most of initialization */
self.xVal = x;
}
return self;
}
-(id) init {
return [self initWithX:0.0f];
}
In this example initWithX: is our main initializer. The other initializer (init) simply calls initWithX: with a default value (in this case 0).
Yes, that's exactly how I do it. One slight change will cut out a line of code:
if (self = [super init]) {
As opposed to:
self = [super init];
if(self) {
For modern Objective-C ...
UDFile.h
#import <Foundation/Foundation.h>
#interface UDFile : NSObject
#property (nonatomic, strong) NSString *name;
- (instancetype)initWithName:(NSString *)name NS_DESIGNATED_INITIALIZER;
#end
UDFile.m
#import "UDFile.h"
#implementation UDFile
- (instancetype)initWithName:(NSString *)name {
self = [super init];
if (self) {
_name = [name copy];
}
return self;
}
- (instancetype)init {
return [self initWithPathname:#""];
}
Sometimes, you want to reuse some initialisation code and modify the behaviour only slightly for specific initialisers. In this case, I do the following:
- (id) init
{
self = [super init];
if (!self) return nil;
// These values are always initialised this way
ivar1 = 10;
ivar2 = #"HellO";
ivar3 = [[NSMutableArray alloc] initWithCapacity:10];
ivar4 = 22;
return self;
}
- (id) initWithIvar4:(int) aValue
{
// call -init on self, which will call -init on super for us, and set
// up ivar1, ivar2, ivar3, and ivar4.
self = [self init];
if (!self) return nil;
// Change ivar4 from the default 22 to whatever aValue is.
ivar4 = aValue;
return self;
}