I am very new to objective-c and im trying to declare a new instance of UITableView
in XCode. Here is my code:
UITableView *mainTable = [[UITableView alloc] init];
and XCode is pointing at the =
and bothering me about a semicolon at开发者_如何学JAVA the end of the declaration statement, which is obviously there.
EDIT:
#import <UIKit/UIKit.h>
@interface TestRunAppDelegate : NSObject <UIApplicationDelegate> {
UITableView *mainTable = [[UITableView alloc] init];
}
You can't make assignments inside your class's interface.
Move the assigment to your app delegate's init
method:
#import <UIKit/UIKit.h>
@interface TestRunAppDelegate : NSObject <UIApplicationDelegate> {
UITableView *mainTable;
}
@end
@implementation TestRunAppDelegate
- (id)init {
if( !(self = [super init]) ){
return nil;
mainTable = [[UITableView alloc] init];
return self;
}
@end
The @interface
block (everything from @interface
to @end
) simply tells other code what to expect from your class. It doesn't do anything itself. Between the curly braces, you declare instance variables, but don't actually create any objects. After the instance variable declaration and before @end
, you declare your methods. Again, you don't implement them. You're simply letting the compiler, and any other code that imports your header, know what they can expect your class to do.
The reason for separating the implementation and interface in this way* is to realize one of the tenets of object-oriented programming. An object essentially tells other objects what it can do (the interface), but makes no statement as to how it will accomplish a task (implementation).
*They are usually put into two separate files but don't actually have to be.
You're trying to instantiate instance variable in @interface. You have to do it in @implementation block.
You can only assign a value to a variable inside a method in your @implementation
. The declaration in the @interface
is basically a 'heads up' to the system.
Addendum: The stuff in the @interface
doesn't actually do anything; it's just a directive for the compiler to know what to look for, some hooks for Interface Builder, and a public statement of what your class does. The part that matters is the @implementation
—but even then, outside of compiler directives such as @synthesize
, only the stuff inside methods count. Objective-C is not procedural; it won't execute every line in order. Compiler directives such as @synthesize
are parsed and processed by the compiler, which in @synthesize
's case creates new methods, and preprocessor directives such as #define
, which are again processed before the runtime system ever sees them. The runtime system can only execute blocks of code—your methods; it has no sense of your entire @implementation
, only the methods of the class. Anything outside of the class is not known to the runtime system, so it wouldn't be valid code. That's why you have to do the assignment inside a method in your implementation.
精彩评论