【问题标题】:Using NSUInteger Input to insertObject:___ atIndex:___使用 NSUInteger 输入到 insertObject:___ atIndex:___
【发布时间】:2014-11-19 18:57:27
【问题描述】:

我正在尝试使用 NSMutableArray 创建一个简单的命令行井字游戏。

使用“getPosition”方法创建了一个名为“Board”的类 (我假设这是获得用户输入的最佳方式) 我要求位置,然后从 int 转换为 NSUInteger)

#import "Board.h"

@implementation Board

-(void)getPosition;
{
    int enteredPosition;
    scanf("%i", &enteredPosition);
    NSUInteger nsEnteredPosition = (NSUInteger ) enteredPosition;
    NSLog(@"Position = %lu", (unsigned long)nsEnteredPosition);
}



#import <Foundation/Foundation.h>
#import "Board.h"


int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSString *currentPlayer;
        NSMutableArray *gameBoard=[[NSMutableArray alloc] initWithCapacity:9];

        for(int i; i<=2; i++)
        {
            if(i %2)
            {
                currentPlayer=@"X";
            }
            else
            {
                currentPlayer=@"O";
            }

        NSLog(@"Player %@, select an open spot 1 - 9 on the board", currentPlayer);
        Board *currentPosition = [[Board alloc] init];
        [currentPosition getPosition];
        [gameBoard insertObject:currentPlayer atIndex:currentPosition]; //this is where i have a problem
        }

据我了解,atIndex 需要一个 NSUInteger 参数,但我收到了错误消息:

"发送'Board *_strong的整数转换指针不兼容" 到“NSUInteger”类型的参数(又名“未分配长”)

【问题讨论】:

    标签: objective-c nsmutablearray nsuinteger


    【解决方案1】:

    您使用currentPosition 作为您的索引,这是一个Board 对象。也许[currentPosition getPosition] 应该返回一个NSUInteger。如果是这样,请尝试像这样重写代码的最后一部分:

    Board *theBoard = [[Board alloc] init];
    NSUInteger currentPosition = [theBoard getPosition];
    [gameBoard insertObject:currentPlayer atIndex:currentPosition]; //this is where i have a problem
    

    【讨论】:

    • 感谢@somegeekintn,但是当我将代码更改为该代码时,我收到以下错误:“Initializing 'NSUInteger”(又名'unsigned long')和不兼容类型void的表达式。是因为我在 Board 类中定义了返回(void)的方法吗?我尝试更改它,但似乎没有帮助。
    • 也许吧。修改显示 Board 类来源的问题可能会有所帮助。
    • 没关系。我想我现在修好了。我需要将我的类头文件和实现文件的 getPosition 方法类型从 (void) 更改为 (int)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多