Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue with removing objects using [NSObject mutableArrayValueForKeyPath:] resulting in a crash. #480

Open
rupertdaniel opened this issue Dec 18, 2024 · 0 comments

Comments

@rupertdaniel
Copy link

rupertdaniel commented Dec 18, 2024

There seems to be an issue with how [NSObject mutableArrayValueForKeyPath:] is maintaining the underlying array when removing objects, resulting in a crash when the operation is performed.

In order to trigger the issue, the array needs more than one item, and the items have to be removed in a specific order.

Here is some test code that can reproduce the issue:

@interface TestObject : NSObject

@property (nonatomic, copy) NSArray *items;

- (void)addItem:(id)item;
- (void)removeItem:(id)item;

@end

@implementation TestObject

- (instancetype)init
{
	if (self = [super init]) {
		self.items = @[];
	}
	
	return self;
}

- (void)addItem:(id)item
{
	[[self mutableArrayValueForKeyPath:@"items"] addObject:item];
}

- (void)removeItem:(id)item
{
	[[self mutableArrayValueForKeyPath:@"items"] removeObject:item];
}

@end

@interface TestDriver : NSObject

- (void)run;

@end

@implementation TestDriver

- (void)run
{
	NSString *s1 = [NSString stringWithFormat:@"Moose1"];
	NSString *s2 = [NSString stringWithFormat:@"Moose2"];
	
	// Removing s1 then s2 works
	TestObject *t1 = [[TestObject alloc] init];
	[t1 addItem: s1];
	[t1 addItem: s2];
	
	[t1 removeItem: s1];
	[t1 removeItem: s2];
	
	// Removing s2 then s1 throws exception
	TestObject *t2 = [[TestObject alloc] init];
	[t2 addItem: s1];
	[t2 addItem: s2];
	
	[t2 removeItem: s2];
	[t2 removeItem: s1];
}

@end

The crash happens here:

1  -[GSArray objectAtIndex:]                          GSArray.m                339  0x7ffed3773139 
2  -[NSMutableArray removeObject:]                    NSArray.m                2385 0x7ffed37bb1db 
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant