6
    NSString * strNil= [NSString stringWithFormat:@"%@",nil];

The result is strNil is @"null"

Well, I want it to be @""

And I want an elegant solution. I know I can just create emptyStringIfNil category method. But that wouldn't work because that function will return nil, instead of @"".

What do you do for this?

Basically I want statements like

NSString * result =[NSString stringWithFormat:@"http://%@/business/api/addOrEditBusiness.php?flag=%@&title=%@&building=%@&latitude=%@&longitude=%@&website=%@&street=%@&city=%@&country=%@%@&originalid=%@&inbuildingaddress=%@&email=%@&zip=%@%@&userid=%@%@",urlServer,strFlag,biz.Title.RobustURLEncodedString,biz.buildingName.RobustURLEncodedString,@(coord.latitude),@(coord.longitude),biz.Website.RobustURLEncodedString,biz.Street.RobustURLEncodedString, biz.City.Name.RobustURLEncodedString, biz.City.Country.Name.RobustURLEncodedString,strPhonesParameter,biz.ID.RobustURLEncodedString,biz.InBui

to show empty everytime the string is nil

For example, if streetAddress is nil, I want &street=&city=Tokyo instead &street=(null)&city=Tokyo

4

3 回答 3

7

I dont know if there is an easier way, but you could just put:

(strName ? strName : @"")

or, more simply put you can use:

strName?:@""

which does the exact same thing.

for each of the strings, which will just place the string in your output if it is not nil, otherwise an empty string.

于 2013-03-20T03:50:12.027 回答
6

You could use a C function instead:

static inline NSString* emptyStringIfNil(NSString *s) {
    return s ? s : @"";
}

Then [NSString stringWithFormat:@"%@", emptyStringIfNil(nil)] returns an empty string.

You could also add a class method to NSString, but I personally like the C approach better.

@interface NSString (EmptyIfNil)
+ (NSString*)emptyStringIfNil:(NSString*)s;
@end

@implementation NSString (EmptyIfNil)
+ (NSString*)emptyStringIfNil:(NSString*)s {
    return s ? s : @"";
}
@end

And then use [NSString emptyStringIfNil:yourString]

于 2013-03-20T03:47:29.563 回答
0

Try this

NSString *strNil1 = [[NSString alloc] init];
strNil1 = @"1";
strNil1  = strNil1 ? strNil1 : @"";
NSLog(@" ==> %@", strNil1);

Output :: ==> 1

NSString *strNil2 = [[NSString alloc] init];

strNil2  = strNil2 ? strNil2 : @"";
NSLog(@" ==> %@", strNil2);

Output :: ==>

Hope, you'll get it.

Thanks.

于 2013-03-20T05:39:21.323 回答