NSNull stringByReplacingOccurrencesOfString:withString: issue with a JSON - ios

i've a problem with parsing a JSON:
in mycallback method i copy object for key "a" in a NSDictionary *test as follow:
[[test sharedManager] MyTestCallback:^(MyTestSessionStatus status, NSDictionary * t, NSError * error){
test = [t objectForKey:#"a"];
}
then in an other method i copy in an array the value
NSArray *temp = [discoveredMedia valueForKeyPath:#"b"];
and then when i try to do
NSString *temp2 = (NSString *)[temp objectAtIndex:0];
but value is -> Printing description of temp2: < null >
and in debugger -> temp2 NSString * class name = NSNull 0x383ed3d0
it crushed when
temp2 = (NSString *)[temp2 stringByReplacingOccurrencesOfString:#"<$size$" withString:#"350"];
in console:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull stringByReplacingOccurrencesOfString:withString:]: unrecognized selector sent to instance 0x383ed3d0'
what's going on?
Thanks

In JSON you have 'null' in dictionary and it will return in objective c not nil but NSNull.
You need to treat NSNull as nil.

I have made a simple NSNull workaround, to avoid crashes on NSNull calls
1) Add this code in your AppDelegate
#import "EXTNil.h"
#import <objc/runtime.h>
+ (id)swizzled_null
{
return [EXTNil null];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
SEL originalSelector = #selector(null);
SEL swizzledSelector = #selector(swizzled_null);
Method originalMethod = class_getClassMethod([NSNull class], originalSelector);
Method swizzledMethod = class_getClassMethod([self class], swizzledSelector);
method_exchangeImplementations(originalMethod, swizzledMethod);
return YES;
}
2) Added (EXTNil and EXTRuntimeExtensions) classes to your project from repo https://github.com/jspahrsummers/libextobjc/tree/master/extobjc
Now You can call any method on NSNull

Related

Objective-C data type issue

I'm not that strong with Objective-C, so this is probably a simple issue. I cannot understand why the the last line in the error completion block is causing an exception:
- (void)sendInappropriateNewsfeedComment:(NSString *)comment newsfeedEventId:(NSString *)newsfeedEventId completion:(void (^)(NSString *, NSInteger))completion error:(void (^)(NSString *, NSInteger))error {
PAInappropriateNewsFeedRequest *inappropriateNewsfeedRequest = [[PAInappropriateNewsFeedRequest alloc] initWithComment:comment newsfeedEventId:newsfeedEventId];
[inappropriateNewsfeedRequest executeWithCompletionBlock:^(id obj) {
completion(#"SUCCESS", (NSInteger)1);
} error:^(NSError *e, id obj) {
NSString * message = [obj objectForKey:#"message"];
error(message, [obj integerForKey:#"code"]);
}];
}
I've also attached a screenshot showing that the "obj" object has a key called "code" that is of type "(long)-1".
What is the proper way to declare the error block and pass the "-1" value back to the call site?
Simply because NSDictionary has no method called integerForKey. That's what "unrecognized selector" means. Selector is basically a method name.
The fact that this can be even compiled is caused by using id for the parameter type. You can call anything on id but it will crash your app if the method does not exist. You should cast obj to a proper type as soon as possible.
NSDictionary *dictionary = (NSDictionary *) obj;
NSString *message = dictionary[#"message"];
NSNumber *code = dictionary[#"code"];
If obj can be a different type, you should make sure to check [obj isKindOfClass:NSDictionary.self] before casting.
The whole solution taking Sulthan's suggestions into account might looks something like this
typedef void (^NewFeedCompletion)(NSString *, NSInteger);
typedef void (^NewsFeedError)(NSString *, NSInteger);
- (void) sendInappropriateNewsfeedComment: (NSString *)comment
newsfeedEventId: (NSString *)newsfeedEventId
completion: (NewFeedCompletion) completion
error: (NewsFeedError) error
{
PAInappropriateNewsFeedRequest *inappropriateNewsfeedRequest = [[PAInappropriateNewsFeedRequest alloc] initWithComment:comment newsfeedEventId:newsfeedEventId];
[inappropriateNewsfeedRequest executeWithCompletionBlock: ^(id obj) {
completion(#"SUCCESS", (NSInteger)1);
} error:^(NSError *e, id obj) {
assert([obj isKindOfClass: NSDictionary.class])
NSDictionary *errorDictionary = (NSDictionary *) obj;
NSString *message = [errorDictionary objectForKey: #"message"];
NSNumber *code = [errorDictionary objectForKey: #"code"]
error(message, [code integerValue]);
}];
}

App crash - when installed from App store but not locally

When i test my app as DEBUG then it works. But when i release to App store and from App Store install the app then it crash.
Therefore i changed the DEBUG RUN method into RELEASE run method for testing.
When i now run as RELEASE run method, then the app crash too (same as APP store Crash). The app crash is pointing at line 19.
How do i fix it? here i am telling to make an DNS (A or AAAA record) self.server = [self.server stringByAppendingString:#".example.com"]; by joining one string with the string i have from line 18.
- (void)myMethodHere:(NSString *)a {
//where a = #"splitme://test1/test2/test3";
NSArray *work_array = [a componentsSeparatedByString:#"splitme://"];
self.use_url =[work_array objectAtIndex:1];
if ([self.use_url length] > 0) {
NSArray *work_array = [self.use_url componentsSeparatedByString:#"/"];
self.server = [work_array objectAtIndex:0];
// -------------------
// CRASH HERE // CRASH HERE
// -------------------
if([self.server length] > 0) {
NSLog(#"!!!!!!!!!!!!!!!!!!!!!! 4 - part 1: %#", self.server); // WORKS
// Here we go CRASHing...
self.server = [self.server stringByAppendingString:#".example.com"];
NSLog(#"!!!!!!!!!!!!!!!!!!!!!! 4 - part 2: %#", self.server); // CRASH CRASH
}
else {
self.server = #"test.example.com";
}
}
else {
NSLog(#"!!!!!!!!!!!!!!!!!!!!!! 9: %#", self.use_url);
}
[self load_later];
}
EDIT 1: Following way of doing let me pass but if i have again self.server outside of this scope then app crash again.
NSString *part1 = self.server;
NSString *part2 = #".example.com";
NSString *result =[part1 stringByAppendingString:part2];
self.server = result;
NSLog(#"!!!!!!!!!!!!!!!!!!!!!! 4 - part 2: %#", self.server);
EDIT 2: crashing on AppDelegate.m, after commenting out the NSLog lines.
2017-04-08 10:32:01.773648+0200 app[344:18271] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2017-04-08 10:32:01.774146+0200 app[344:18271] [MC] Reading from public effective user settings.
2017-04-08 10:32:01.778647+0200 app[344:18271] -[__NSArrayM length]: unrecognized selector sent to instance 0x1740457c0
2017-04-08 10:32:01.778888+0200 app[344:18271] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM length]: unrecognized selector sent to instance 0x1740457c0'
*** First throw call stack:
(0x18a956fd8 0x1893b8538 0x18a95def4 0x18a95af4c 0x18a856d2c 0x100006f78 0x1000076e8 0x1000066cc 0x190a85f9c 0x190a85b78 0x190a8c3f8 0x190a89894 0x190afb2fc 0x190d038b4 0x190d092a8 0x190d1dde0 0x190d0653c 0x18c4ff884 0x18c4ff6f0 0x18c4ffaa0 0x18a905424 0x18a904d94 0x18a9029a0 0x18a832d94 0x190af045c 0x190aeb130 0x100007d78 0x18984159c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
EDIT 3: Crashing NSString not NSString even with explicit cast
- (void)setServer:(NSString *)value
{
if (value != nil && ![value isKindOfClass:[NSString class]]) {
NSLog(#"!!!!!!!!!!!lol!!!!!!!!!!!!! Bug! Set breakpoint here!");
}
self.server = value;
}
NSArray *work_array = [self.use_url componentsSeparatedByString:#"/"];
NSString *setServerURL =(NSString *) [work_array objectAtIndex:0];
[self setServer:setServerURL];
EDIT 4: Crashing
- (void)myMethodHere:(NSString *)a {
NSArray *work_array = [a componentsSeparatedByString:#"test://"];
id objectOne = [work_array objectAtIndex:1];
if ([objectOne isKindOfClass:[NSString class] ] ) {
NSString *objectOneIntoString = objectOne;
self.use_url = (NSString *) objectOneIntoString;
}
if ([self.use_url length] > 0) {
NSLog(#"3: %#", self.use_url);
NSArray *work_array = [self.use_url componentsSeparatedByString:#"/"];
id objectTwo = [work_array objectAtIndex:0];
if ([objectTwo isKindOfClass:[NSString class] ]) {
NSString *objectTwoIntoString = objectTwo;
self.server = objectTwoIntoString;
}
if([self.server length] > 0) {
NSLog(#"4 - part 1: %#", self.server);
NSString *part1 = self.server;
NSString *part2 = #".example.com";
NSString *result = (NSString *) [part1 stringByAppendingString:part2];
self.server = result;
NSLog(#"4 - part 2: %#", self.server);
}
else {
self.server = #"dns.example.com";
NSLog(#"5:%#", self.server);
}
NSLog(#"8: %#", self.server);
}
else {
NSLog(#"9: %#", self.use_url);
}
NSLog(#"10: %#", self.use_url);
}
The error message in your pastebin is:
2017-04-08 10:32:01.778647+0200 app[344:18271] -[__NSArrayM length]: unrecognized selector sent to instance 0x1740457c0
2017-04-08 10:32:01.778888+0200 app[344:18271] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM length]: unrecognized selector sent to instance 0x1740457c0'
This tells you that there was an array on which you called length. So if it really is related to your server property then you are accidentally storing an NSArray there somewhere.
Here's an idea on how to catch that: implement the setServer: method and check whether the type is correct.
- (void)setServer:(NSString *)value
{
if (value != nil && ![value isKindOfClass:[NSString class]]) {
NSLog(#"Bug! Set breakpoint here!");
}
_server = value;
}
Edit: You implemented your setter incorrectly and would normally have produced an endless recursion. So let's start from scratch:
I assume you have a property defined like this:
#property (strong) NSString * server; // Or maybe "copy"
If your property does not look like this you need to tell us!
Then you implement the setter exactly like this:
- (void)setServer:(NSString *)value
{
if (value != nil && ![value isKindOfClass:[NSString class]]) {
NSLog(#"Bug! Set breakpoint here!");
}
_server = value;
// DO NOT DO self.server = value HERE!
}
Then you can just do self.server = blabla; in the rest of your code and if your code sets something that is not a string the NSLog will be hit. So set a breakpoint there!
Edit 2:
Now I've seen in another comment of yours what's wrong…
#property (assign, nonatomic) NSString *server;
The assign does not retain the object! You need to use strong or (in the case if NSString *) copy. As it is, the following will happen:
You assign an object to server.
Since it is not retained, the object is deallocated soon.
But server still has a pointer to that memory location.
Two things can happen now:
Either a new, different object is created at memory location before you access the property. You now get an unexpected object back. Calling methods on this object may work or it may crash since the object does not know the method.
Or the memory location is deemed invalid and you get a crash right away.
Never use assign with objects!
-[__NSArrayM length]: unrecognized selector sent to instance 0x1740457c0
self.server class is NSArray .must string length

NSCFNumber escapedString Error with a NSDictionary

So I'm getting this error when creating a NSDictionary:
DLog(#"hiliteID: %# | regionID: %#", hiliteID, regionID);
if ([hiliteID isKindOfClass:[NSNumber class]]) {
DLog(#"hititeID is a number");
}
if ([hiliteID isKindOfClass:[NSString class]]) {
DLog(#"hiliteID is a string");
}
if ([regionID isKindOfClass:[NSNumber class]]) {
DLog(#"regionID is a number");
}
if ([regionID isKindOfClass:[NSString class]]) {
DLog(#"regionID is a string");
}
NSDictionary *regionDictionary = [NSDictionary dictionaryWithObject:regionID forKey:hiliteID];
DLog(#"regionDictionary: %#", regionDictionary);
id result = [self.serverCall XMLRPCCall:kSaveHilitedObjects withObjects:#[self.mapContext, regionDictionary]];
What is logged:
DEBUG | hiliteID: 160399 | regionID: 950
DEBUG | hititeID is a number
DEBUG | regionID is a number
DEBUG | regionDictionary: {
160399 = 950;
}
DEBUG -[__NSCFNumber escapedString]: unrecognized selector sent to instance 0x7947f5d0
DEBUG *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber escapedString]: unrecognized selector sent to instance 0x7947f5d0'
0x7947f5d0 has a value of 160399 so it is hiliteID.
hiliteID is a returned value from our server and is set as a NSString. I cast it to a NSNumber:
NSArray *hiliteIDs = [result allKeys];
if ([[hiliteIDs firstObject] isKindOfClass:[NSString class]]) {
return [NSNumber numberWithInteger:[[hiliteIDs firstObject] integerValue]];
}
else if ([[hiliteIDs firstObject] isKindOfClass:[NSNumber class]]) {
return [hiliteIDs firstObject];
}
As far as I know, there is no issue with what I am doing here.
the line:
id result = [self.serverCall XMLRPCCall:kSaveHilitedObjects withObjects:#[self.mapContext, regionDictionary]];
I've used this class dozens of times in the code and never had an issue.
What can be causing the error?
reason: '-[__NSCFNumber escapedString]: unrecognized selector sent to instance 0x7947f5d0'
Someone trying to call -escapedString method from NSNumber class, so it seems like the problem is that you passing NSNumber argument when NSString required. Try to use only NSString values inside your NSDictionary.
Whatever XMLRPCCall:withObjects: is calling an invalid method. I would recommend making all inputs into this method into NSStrings so that that call doesn't internally call methods on NSNumbers that NSNumber isn't capable of responding to.
NSString *regionIDString = [regionID stringValue];
NSString *hiliteIDString = [hiliteID stringValue];
NSDictionary *regionDictionary = [NSDictionary dictionaryWithObject:regionIDString forKey:hiliteIDString];

NSData AES trigger unrecognized selector sent to instance error

I use a AES library from github NSData+AES by nicerobot's objc
My codes are below :
-- AESLib.h--
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonCrypto.h>
#interface AESLib : NSObject
-(NSData *) encodeAES:(NSData *) argSource;
#end
-- AESLib.m --
-(NSData *) encodeAES:(NSData *) argSource
{
NSString APIV1_AES_KEY = #"//AAAAAAAAAAAAAAAAAAAAAA"; // 24 char
NSString APIV1_AES_IV = #"//BBBBBBBBBBBBBB"; // 16 char
NSData *key = [NSData dataWithBytes:APIV1_AES_KEY.UTF8String length:strlen(APIV1_AES_KEY.UTF8String)];
NSData *iv = [NSData dataWithBytes:APIV1_AES_IV.UTF8String length:strlen(APIV1_AES_IV.UTF8String)];
NSData *encData;
#try {
encData = [argSource encrypt:key withInitial:iv andPadding:kCCOptionPKCS7Padding];
// Error Here
return encData;
}
#catch (NSException *exception) {
NSLog(#"Exception : %#", [exception reason]);
}
return nil;
}
//Error
> XCode trigger error 2013-10-22 16:15:58.206 Aessample[2913:c07]
> -[NSConcreteMutableData encrypt:withInitial:andPadding:]: unrecognized selector sent to instance 0x7523300 2013-10-22 16:15:58.207
> Aessample[2913:c07] Exception : -[NSConcreteMutableData
> encrypt:withInitial:andPadding:]: unrecognized selector sent to
> instance 0x7523300
Why this error happen?
--- Add to NSMutableString
Thank you NSMutableString.
I did tried again likewise your answers, but my code triggers still same errors.
Help again NSMutableString plz.
Delete the category files and add them again checking the target.

performSelector afterDelay with multiple arguments error

I´m having some problems with performSelector method on this code:
This method are in other class called "JSONMethods":
+(void)sendPostMsgWithMultipleArguments:(NSArray *)myArgs {
[self sendPostMsg:[myArgs objectAtIndex:0]:[myArgs objectAtIndex:1]];
}
Then, on another class I have the call:
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Loading...";
JSONMethods *methods = [[JSONMethods alloc]init];
NSArray *arguments = [[NSMutableArray alloc]initWithObjects:#"http://localhost/promos/txFirmas.php",[NSString stringWithFormat:#"sensor=%d",tableViewNumber], nil];
[methods performSelector:#selector(sendPostMsgWithMultipleArguments:)
withObject:arguments
afterDelay:3.0];
NSString *tit = [NSString stringWithFormat:#"Sign: %d",tableViewNumber];
self.title = tit;
}
I would like wait until the "sendPostMsgWithMultipleArguments:" finish for change the title, how I can make it?
When I test this, mi app crash and show me this by console:
2012-08-17 12:09:15.966 MapaProject[524:11603] -[JSONMethods sendPostMsgWithMultipleArguments:]: unrecognized selector sent to instance 0x7c85b70
2012-08-17 12:09:15.968 MapaProject[524:11603] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[JSONMethods sendPostMsgWithMultipleArguments:]: unrecognized selector sent to instance 0x7c85b70'
*** First throw call stack:
(0x133a022 0x2016cd6 0x133bcbd 0x12a0ed0 0x12a0cb2 0xa1c85d 0x130e936 0x130e3d7 0x1271790 0x1270d84 0x1270c9b 0x15db7d8 0x15db88a 0xf6626 0x236d 0x20c5)
terminate called throwing an exception
Can you help me?
Thanks in advance :)
Change +(void)sendPostMsgWithMultipleArguments:(NSArray *)myArgs
to -(void)sendPostMsgWithMultipleArguments:(NSArray *)myArgs
or even better change
[methods performSelector:#selector(sendPostMsgWithMultipleArguments:) withObject:arguments afterDelay:3.0];
to [[methods class] performSelector:#selector(sendPostMsgWithMultipleArguments:)
withObject:arguments
afterDelay:3.0];
NSArray * mutArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:0],[NSNumber numberWithInt:2], nil]
[self performSelector:#selector(loadMore:) withObject:mutArray afterDelay:1.9];
-(void)loadMore:(NSArray *)array
{
NSNumber * myNumber = [array objectAtIndex:0];
NSNumber * myNumber2 = [array objectAtIndex:1];
}
In swift 3
You can make dictionary to save multiple arguments and pass it with the selector
let argumentsDict = ["arg1Key": arg1Value, "arg2Key": arg2Value] as [String : Any]
perform(#selector(selectorWithMultipleArg), with: argumentsDict, afterDelay: 3.0)
And inside the selector function, take out values using guard and use them. I am using 2 different type arguments to explain better .i.e. Int and String
func selectorWithMultipleArg(_ arguments: [String: Any]) {
guard let arg1Value = arguments["arg1Key"] as? Int else {
fatalError("Invalid value 1")
}
guard let arg2Value = arguments["arg2Key"] as? String else {
fatalError("Invalid value 2")
}
print("Value 1: \(arg1Value)")
print("Value 2: \(arg2Value)")
}
I hope this would help you

Resources