开发者

Objective C shenanigans

开发者 https://www.devze.com 2023-04-05 19:35 出处:网络
In my quest to be the grandmaster of Objective C, I keep running into it\'s subtleties, which Iwant to share with ya\'ll and gain an understanding why

In my quest to be the grandmaster of Objective C, I keep running into it's subtleties, which I want to share with ya'll and gain an understanding why

1) I have two init methods, the one that is inherited by NSObject for my Objective C class and one is a custom method that I create off my own, let's say

initCustomMethod:(int)par1 argument2:(int)par2;

My Aim is to call initCustomMethod through the provided init method, essentially

-(id)init{
    return [self initCustomMethod:1 argument2:3];
}

Naturally, maintaining the order, I have init appearing before initCustomMethod in the .m file. Xcode warns me telling me that the initCustomMethod is not found, I go ahead and shuffle the order and have init appearing after initCustomMethod is declared and there is no such warning message anymore and everything is fine.

I concur that the order is important since it's essentially derived from C, however I am not sure of this. Because, i shuffled the order o开发者_JAVA技巧f some properties and their custom methods, with the properties @synthesize being declared after the custom setter method for a given property, but there was no such error replica.

Can anyone point out the malice here?

Thanks guys!!!


Very cool guys, thanks for helping me out with this. Also, since I have a custom init method, I am initializing the super in this method and using the original init method to call the custom init method.

Anything wrong with this?


Before you reference it anywhere, you should declare initCustomMethod:argument2 in your interface, which would usually be in your header file.

For example, you would usually have a .h file that looks like:

@interface MyClass
{
    //instance variables
    int anInstanceVariable;
}

// properties
@property (nonatomic, assign) int aProperty;

// methods
-(id)initCustomMethod:(int)par1 argument2:(int)par2;

@end

And if you did this, the order in which you define init and initCustomMethod:argument2: won't matter. This is because the declaration tells the compiler that you are going to define the method, and what it will look like, so it isn't confused when you use it later.


It's a bad idea in Objective-C to use a function or a method before it is either declared or defined. Putting initCustomMethod:argument2: before init means that the former is already defined in the latter. But if you'd just declare it in the header, it wouldn't matter which order they went in.


Add your custom method name in your header file - the compiler just goes through things in order. If you don't have a forward declaration, the compiler won't know what to do with that call. You're going to need to put it in the header if you want other parts of your program to be able to call it anyway.

0

精彩评论

暂无评论...
验证码 换一张
取 消