Outside of method error pg117


#1

Why do i have this error? [quote]Cannot assign to self outside of a method in the init family[/quote]
Error relate to this line of code. [quote]self =[super init][/quote] I’m using Xcode 4.5 iphone simulator 6.0.

[code]#import “BNRMapPoint.h”

@implementation BNRMapPoint
@synthesize coordinate, title;

=(id) initWithCoordinate: (CLLocationCoordinate2D)c title: (NSString *)t
{
self = [super init]; // error here
if(self) {
coordinate = c;
[self setTitle: t];
}
return self;
}

@end [/code];

#2

Looks like you were (touch) typing at maximum speed and whizzed past that syntax error!
(Unless there is new syntax that I am not aware of in the latest and greatest version of the compiler.)

But the error you are getting is a bit strange, given that syntax error. It seems to suggest that you are assigning to self outside of an init… method.


#3

Thanks for your reply. The code is correct on my Xcode compiler. I just mistakenly typed the wrong code here at this post (I should’ve copied and paste but I didn’t) I’m still hoping for an answer concerning my outside method error.


#4

This simple example might help you understand:

#import <Foundation/Foundation.h>

@interface Foo : NSObject
{
   id _bar;
}
@end

@implementation Foo

- (id)initWithBar:(id)bar
{
    self = [super init];  // Ok here because we are inside a method in the init family
    if (self)
    {
         _bar = bar;
    }
    return self;
}

- (id)resetWithBar:(id)bar
{
    self = [super init]; // Not Ok here because we are not inside a method in the init family
    if (self)
    {
         _bar = bar;
    }
    return self;
}

@end

#5

Ibex thanks for your help! I do understand what you’re saying. I found my error, and "self” was outside the method in the init family because a syntax error. I did not capitalize parts of the selector name correctly, both in the declaration and in the method’s definition. Both had -(id)initwithCoordinate:(CLLocationCoordinate2D c title: (NSString *) t. But the “w” in both should’ve been capitalized like this -(id)intWithCoordinate(CLLocationCoordinate2D c title:(NSString *) Not doing this lead to the “cannot assign to “self” outside of a method in the init family.” Interesting, if the method definition was a lower case “c” as in coordinate, then an incomplete implementation warning would show too (surprising!). Of course I wasn’t getting that warning. I’m not sure what method X-code uses to determine errors but its something to keep in mind when attempting to debug your program. I should’ve been more diligent concerning obvious syntax errors. That is not usually my problem when writing code. By the way, it would’ve been better if I had post my code verbatim (copy and paste); knowing one you guys would’ve spotted my syntax error right away.