หนึ่งแปลงNSIntegerเป็นNSStringประเภทข้อมูลได้อย่างไร
ฉันลองทำสิ่งต่อไปนี้โดยที่เดือนคือNSInteger:
NSString *inStr = [NSString stringWithFormat:@"%d", [month intValue]];
หนึ่งแปลงNSIntegerเป็นNSStringประเภทข้อมูลได้อย่างไร
ฉันลองทำสิ่งต่อไปนี้โดยที่เดือนคือNSInteger:
NSString *inStr = [NSString stringWithFormat:@"%d", [month intValue]];
คำตอบ:
NSIntegers ไม่ใช่อ็อบเจ็กต์ที่คุณส่งไปlongเพื่อให้ตรงกับนิยามสถาปัตยกรรม 64 บิตปัจจุบัน:
NSString *inStr = [NSString stringWithFormat: @"%ld", (long)month];
[@(integerValue) stringValue]เป็นแนวทางที่สะอาดกว่า
วิธี Obj-C =):
NSString *inStr = [@(month) stringValue];
An NSIntegerมีวิธีการstringValueที่สามารถใช้ได้แม้กับตัวอักษร
NSString *integerAsString1 = [@12 stringValue];
NSInteger number = 13;
NSString *integerAsString2 = [@(number) stringValue];
ง่ายมาก. ไม่ใช่เหรอ?
var integerAsString = String(integer)
%zdใช้งานได้กับ NSIntegers ( %tuสำหรับ NSUInteger) โดยไม่มีการแคสต์และไม่มีคำเตือนบนสถาปัตยกรรมทั้ง 32 บิตและ 64 บิต ฉันไม่รู้ว่าทำไมจึงไม่ใช่ " วิธีที่แนะนำ "
NSString *string = [NSString stringWithFormat:@"%zd", month];
หากคุณสนใจว่าเหตุใดจึงได้ผลโปรดดูคำถามนี้
วิธีทำง่ายๆ:
NSInteger value = x;
NSString *string = [@(value) stringValue];
ที่นี่@(value)จะแปลงสิ่งที่กำหนดNSIntegerให้เป็นNSNumberวัตถุที่คุณสามารถเรียกใช้ฟังก์ชันที่ต้องการstringValueได้
เมื่อรวบรวมโดยรองรับarm64สิ่งนี้จะไม่สร้างคำเตือน:
[NSString stringWithFormat:@"%lu", (unsigned long)myNSUInteger];
คุณยังสามารถลอง:
NSInteger month = 1;
NSString *inStr = [NSString stringWithFormat: @"%ld", month];
ได้รับคำตอบแล้ว แต่คิดว่าสำหรับบางสถานการณ์นี่จะเป็นวิธีที่น่าสนใจในการรับสตริงจาก NSInteger
NSInteger value = 12;
NSString * string = [NSString stringWithFormat:@"%0.0f", (float)value];
NSNumber อาจดีสำหรับคุณในกรณีนี้
NSString *inStr = [NSString stringWithFormat:@"%d",
[NSNumber numberWithInteger:[month intValue]]];
Format specifies type 'int' but the argument has type 'NSInteger *'(aka 'int *')เรื่อย ๆ ตามเอกสารของ Appleฉันไปด้วยNSString *inStr = [NSString stringWithFormat:@"%d", (int)month];