Better way to get the user's name from device?

前端 未结 6 1483
耶瑟儿~
耶瑟儿~ 2020-12-09 05:11

I made a function that extracts a user name from the device name.

The idea is to skip setup steps to allow the user to go straight to play

6条回答
  •  时光取名叫无心
    2020-12-09 05:40

    Here is an alternative, that gets all names. Also, it does not remove 's' at the end of languages that uses "de" or "'s". Also, it capitalizes the first letter of each name.

    Method implementation:

    - (NSArray*) newNamesFromDeviceName: (NSString *) deviceName
    {
        NSCharacterSet* characterSet = [NSCharacterSet characterSetWithCharactersInString:@" '’\\"];
        NSArray* words = [deviceName componentsSeparatedByCharactersInSet:characterSet];
        NSMutableArray* names = [[NSMutableArray alloc] init];
    
        bool foundShortWord = false;
        for (NSString *word in words)
        {
            if ([word length] <= 2)
                foundShortWord = true;
            if ([word compare:@"iPhone"] != 0 && [word compare:@"iPod"] != 0 && [word compare:@"iPad"] != 0 && [word length] > 2)
            {
                word = [word stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[word substringToIndex:1] uppercaseString]];
                [names addObject:word];
            }
        }
        if (!foundShortWord && [names count] > 1)
        {
            int lastNameIndex = [names count] - 1;
            NSString* name = [names objectAtIndex:lastNameIndex];
            unichar lastChar = [name characterAtIndex:[name length] - 1];
            if (lastChar == 's')
            {
                [names replaceObjectAtIndex:lastNameIndex withObject:[name substringToIndex:[name length] - 1]];
            }
        }
        return names;
    }
    

    Usage:

    // Add default values for first name and last name
    NSString* deviceName = [[UIDevice currentDevice] name];
    NSArray* names = [self newNamesFromDeviceName:deviceName];
    // This example sets the first and second names as the text property for some text boxes.
    [self.txtFirstName setText:[names objectAtIndex:0]];
    [self.txtLastName setText:[names objectAtIndex:1]];
    [names release];
    

提交回复
热议问题