我一直在使用objective-c做一件事,但我是这个语言的初学者,这就是我所做的:
有一个名为“firstviewclass”的类,它控制着我的第一个视图,在这个视图中有一个用户放置数字的文本字段。 textfield在firstviewclass.h中,名为“setNumber”。还有另一个名为“secondviewclass”的类控制着第二个视图,在这个视图中有一个标签位于secondviewclass.h中,我希望这个标签能够重现用户放在文本域中的值。第一个观点。我的代码:
firstviewclass.h:
#import <UIKit/UIKit.h>
@interface firstviewclass : UIViewController
@property (strong, nonatomic) IBOutlet UITextField *setNumber;
- (IBAction)gotonextview:(id)sender;
@end
secondviewclass.h:
#import <UIKit/UIKit.h>
#import "firstviewclass.h"
@interface secondviewclass : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *labelthatrecivesthetextfieldvalue;
@end
secondviewclass.m:
#import "secondviewclass.h"
#import "firstviewclass.h"
@implementation secondviewclass
@synthesize labelthatrecivesthetextfieldvalue;
-(void)viewDidLoad{
[super viewDidLoad];
firstviewclass *object = [[firstviewclass alloc] init];
NSString *string = [[NSString alloc] initWithFormat:@"%i", [object.setNumber.text intValue]];
labelthatrecivesthetextfieldvalue = string; //here is where that error appears "incompatible pointer types assigning to 'UILabel *__weak' to 'NSString *__strong'"
}
@end
我已经改变了你告诉我改变的内容,但是当我在模拟器上测试它在文本字段中输入的任何数字时,它在标签中显示为0 ...我真的不知道该怎么做!
答案 0 :(得分:11)
应该是:
labelthatrecivesthetextfieldvalue.text = string;
引擎盖下:
在xib实例化UILabel
并使用IBOutlet
关键字获取其引用之后,您将尝试使用UILabel
指针指向已分配和实例化的内存空间对于NSString
,这就是你遇到这个问题的原因。您可能也确实收到了关于您尝试执行的任务的警告:
labelthatrecivesthetextfieldvalue = string;
您应该始终尝试修复警告。
你想要什么:
您只是希望UILabel
显示您刚刚创建的NSString
,为此您应该使用UILabel's
text属性。
答案 1 :(得分:3)
您收到该错误是因为您将标签指向字符串。它们属于不同的类别,所以这是不允许的。你的真正含义是你希望标签上的文字取字符串的值。因此,您需要设置标签的文本字段:
labelthatrecivesthetextfieldvalue.text = string;
我为之前的错误回答道歉。
顺便提一下,您还应该考虑使用camelCase来命名变量。这是objective-c的惯例。即改为称之为labelThatRecievesTheTextFieldValue
。这不会影响代码的工作能力,只是约定。