【问题标题】:warning: assignment from distinct Objective-C type警告:来自不同 Objective-C 类型的赋值
【发布时间】:2010-02-25 22:32:53
【问题描述】:

我已经查看了有关此错误的所有先前问题和答案,但我无法弄清楚我做错了什么。有人可以帮忙吗?

@synthesize myScrollView;
@synthesize mathsPracticeTextArray;

-(void)loadText
{
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *textFilePath = [bundle pathForResource:@"mathspractice" ofType:@"txt"];
    NSString *fileContents = [NSString stringWithContentsOfFile:textFilePath];
    mathsPracticeTextArray = fileContents;

}

- (void)viewDidLoad {

    [super viewDidLoad];

    myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    myScrollView.contentSize = CGSizeMake(320, 960);
    myScrollView.pagingEnabled = FALSE;    
    myScrollView.scrollEnabled = TRUE;
    myScrollView.backgroundColor = [UIColor whiteColor];

    *[self.view addSubview:myScrollView];
    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,100,960,40)];
    myLabel.text = [mathsPracticeTextArray componentsJoinedByString:@" "];
    [myScrollView addSubview:myLabel];
    [myLabel release];*
}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

}

- (void)viewDidUnload {
}


- (void)dealloc {

    [myScrollView release]; 
    [mathsPracticeTextArray release];
    [super dealloc];

}

@end

【问题讨论】:

  • 能把调试器的日志放上来吗?
  • 我从调试器得到的只是“会话开始”,它实际上编译得很好,只是一个警告,但它没有显示我来自 mathspractice.txt 的文本
  • 在IB中需要标签吗?
  • @Charles:告诉我们哪一行导致了警告,以及所有变量的声明类型如何?目前myScrollViewmathsPracticeTextArray 的类型没有指定。
  • @Charles Marsh:标签不能包含空格,所以写objective-c而不是objective c。由于objective-c 在他们感兴趣的标签列表中,这将确保更多的人会看到您的问题。

标签: objective-c nsarray compiler-warnings


【解决方案1】:

我猜mathsPracticeTextArray 被声明为NSArray*NSMutableArray*,在这种情况下为它分配NSString*(就像在-(void)loadText 中发生的那样)将导致您在标题中提到的警告。

警告很清楚正在发生的事情:NSString 与 NSArray 不同,您不能将一个视为另一个。当您将错误类型的对象分配给变量时,您发送给该对象的许多消息将无法处理,您的应用程序将失败。

【讨论】:

  • 这样吗? -(void)loadText { NSBundle *bundle = [NSBundle mainBundle]; NSString *textFilePath = [bundle pathForResource:@"mathspractice" ofType:@"txt"]; NSArray *fileContents = [NSString stringWithContentsOfFile:textFilePath]; mathsPracticeTextArray = 文件内容; }
  • 代码在 cmets 中永远无法正常工作;太乱了。更改fileContents 的类型只会将问题转移到不同的行,因为它现在将字符串存储为数组。看NSArraydeveloper.apple.com/mac/library/documentation/Cocoa/Reference/…)的方法。此外,stringWithContentsOfFile: 已弃用 (developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Reference/…)。
猜你喜欢
  • 2010-10-06
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
  • 2011-04-14
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
相关资源
最近更新 更多