w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How do I cast void* to NSString without getting a Runtime Error, in Objective C?

The problem is the extra dereference: you are passing a pointer to NSString*, which is itself a pointer.

You can fix this either by adding an extra dereference in voidTest:

NSString* value = *((__unsafe_unretained NSString

or by passing testString instead of &testString in the caller.

Neither of these solutions is ideal, because it forces a cast. Generally speaking, void* should be reserved for calls to C functions. When calling Objective-C to Objective-C, you could use the id type instead, which tells the compiler that you are passing an Objective-C object.

-(void)voidTest:(void*)ptr {
    NSString *val = *((__unsafe_unretained NSString **)(ptr));
    NSLog(@"%@", val);

-(void)testVoid {
    NSString *str = @"Hello";
    [self voidTest:&str];

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.