Skip to content

Instantly share code, notes, and snippets.

@623637646
Last active May 13, 2020 15:01
Show Gist options
  • Save 623637646/4925c27ebf1e43e9762a438c70213f3d to your computer and use it in GitHub Desktop.
Save 623637646/4925c27ebf1e43e9762a438c70213f3d to your computer and use it in GitHub Desktop.
How to change the return value (for object) with Aspects's AspectPositionInstead. Refer to: https://www.jianshu.com/p/5ba69f35e034
@interface MyObject : NSObject
@property NSString *name;
@end
@implementation MyObject
-(void)dealloc
{
NSLog(@"dealloc");
}
@end
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSError *error = nil;
[self aspect_hookSelector:@selector(getMyObject) withOptions:AspectPositionInstead usingBlock:^(id<AspectInfo> info){
NSInvocation *invocation = info.originalInvocation;
__unsafe_unretained MyObject *original = nil;
[invocation invoke];
[invocation getReturnValue:&original];
NSAssert([original.name isEqualToString:@"AAAAA"], @"");
MyObject *new = [[MyObject alloc] init];
new.name = @"BBBBB";
objc_setAssociatedObject(invocation, _cmd, new, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[invocation setReturnValue:&new];
} error:&error];
for (int i = 0; i < 100; i++) {
MyObject *a = [self getMyObject];
NSAssert([a.name isEqualToString:@"BBBBB"], @"");
}
return YES;
}
- (MyObject*)getMyObject
{
MyObject *a = [[MyObject alloc] init];
a.name = @"AAAAA";
return a;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment