在我的xcode项目中包含Objective C类的问题

问题描述 投票:0回答:5

我对Objective C较陌生,大约有1年的经验,在尝试向我的项目中添加类时遇到了一个问题。当我添加一个包含XIB文件的UIViewController子类类时,我一点都没有问题,xcode可以很好地工作。

但是,我尝试向带有以下.h和.m文件的名为Test的项目中添加一个简单的Objective-C类,并且遇到了这样的问题:代码可以正确编译和生成,但是TestMethod方法始终返回nil。这里可能出什么问题?

Test.h

#import <Foundation/Foundation.h>

@class Test;

@interface Test : NSObject {

}

- (NSString *)TestMethod;

@end

Test.m

#import "Test.h"

@implementation Test

- (NSString*)TestMethod {
    return @"Test";
}

@end

在带有XIB文件的UIViewController子类中,该子类可以正常工作,但是当我尝试将Test类包含在其中时,方法TestMethod不返回任何内容,即使它被编码为始终返回相同的字符串:

#import "Test.h"

Test *testobject;

// this compiles and builds but returns nothing
NSString *testString = [testobject TestMethod];
iphone ios objective-c xcode subclass
5个回答
3
投票

您错过了分配+初始化。

使用

Test *testobject=[[Test alloc] init];

Test *testobject=[Test new];

无论何时未初始化对象,您都将获得nil值。

编辑:

ARC中:默认已初始化。

MRC中:该值可能未初始化(垃圾值)。


1
投票

TestMethod不会重播nil-testobject为零。

更改

Test *testobject;

to

Test *testobject = [[Test alloc] init];


1
投票

您尚未创建Test的实例,因此testObject仅保留nil。您需要将Test的实例分配给变量,以执行所需的操作。


0
投票

您也可以采用这种方法

//Test.h

#import <Foundation/Foundation.h>

@class Test;

@interface Test : NSObject {
}
- (id)init;
-(NSString*)TestMethod;

@end

现在在您的Test.m文件中

// Test.m

#import "Test.h"

@implementation Test


- (id)init {

     if (self=[super init]) {

     }
     return self;
}

-(NSString*)TestMethod {
return @"Test";
}

@end

现在,如果要在另一个类中调用此测试类,则必须创建一个测试类的实例。

Test *testobject = [[Test alloc] init];

NSString *testString = [testobject TestMethod];

0
投票

要访问类的任何方法/属性,首先需要使用alloc / new方法为该类的对象分配内存。

由于您创建了该类类型的变量<Test *testobject>。但是变量没有分配任何内存,默认情况下为零。使用“ nil”可以在目标C中调用任何方法。它不会崩溃。但是它将返回nil。

因此,在访问任何对象之前,您必须为该对象创建内存

Test *testobject = [Test alloc];

使用默认构造函数(init,initWith等)初始化对象

[testobject init];

现在对象已准备好调用实例方法/ setter / getter等...

NSString *testString = [testobject TestMethod];
© www.soinside.com 2019 - 2024. All rights reserved.