NSMutableString:rangeOfString:奇怪的NSRange结果

时间:2013-01-04 23:24:01

标签: objective-c

试图找出NSMutableString:rangeOfString:为什么返回非常奇怪的结果。 NSLog向​​我展示了这样的结果:

location = 9223372036854775807 length = 0:这是一个测试

我的测试字符串不包含“@@@”,所以我希望location = 0 length = 0。奇怪的位置不断出现,直到字符串实际包含“@@@”,然后位置和长度是正确的。我在下面的代码片段中遗漏了什么?

ServerPacketMotd.h

typedef struct _serverPacketMotdStruct
{
    int8_t  type;           /* SP_MOTD */
    int8_t  pad1;
    int8_t  pad2;
    int8_t  pad3;
    int8_t  line[80];
} serverPacketMotdStruct;

ServerPacketMotd.m

#import "ServerPacketMotd.h"

@interface ServerPacketMotd()
{
    NSMutableString *buffer;
}
@end

@implementation ServerPacketMotd

- (id)init
{
    if( !( self = [super init] ) )
        return nil;

    buffer = [[NSMutableString alloc] init];

    return self;
}

- (NSMutableData *)handlePacket:(NSData *)data withTag:(long)tag
{
    serverPacketMotdStruct gamePacket;
    uint16_t size = sizeof(serverPacketMotdStruct);
    NSRange packetWindow = NSMakeRange(0, size);
    NSRange atAtAt = NSMakeRange(0,0);

    while (expression)
    {
        [data getBytes:&gamePacket range:packetWindow];
        [buffer appendFormat:@"%s\n", gamePacket.line];

        atAtAt = [buffer rangeOfString:@"@@@"];
        NSLog(@"XXX location=%lu length=%lu:%@", atAtAt.location, atAtAt.length, buffer);
}

1 个答案:

答案 0 :(得分:4)

检查是否atAtAt.location == NSNotFound。位置0表示在位置0找到字符串,但这并不意味着找不到它。