Task: I want to create a NSMutableArray which would hold pointers to CGPoint structures, and then use these pointers in other objects (custom-made, inherited from NSObject) and arrays, so that when I change actual values behind the pointers in the NSMutableArray, it would be seen from everywhere. I don't like the idea of encapsulating it in NSValue since that would break the functionality as I want it.
Some code now:
// Triangle.h
@interface Triangle : NSObject
{
CGPoint *p1;
CGPoint *p2;
CGPoint *p3;
}
@property (nonatomic) CGPoint *p1;
@property (nonatomic) CGPoint *p2;
@property (nonatomic) CGPoint *p3;
@end
// @synthesize in Triangle.m for p1, p2, p3
// somewhere in MyCustomView.m
CGFloat *MRatio = 3.0f; // some values
CGFloat *NRatio = 5.0f; // doesn't matter
rawPoints = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < N; i++)
{
for (NSInteger j = 0; j < M; j++)
{
CGPoint p = CGPointMake(j * MRatio, i * NRatio);
[rawPoints addObject:(__bridge id)&p]; // *** crashes here
}
}
Triangle *t = [[Triangle alloc] init];
t.p1 = (__bridge CGPoint *)([rawPoints objectAtIndex:0]);
NSLog(@"%@", NSStringFromCGPoint(*t.p1)); // original value
CGPoint *pp1 = (__bridge CGPoint *)([rawPoints objectAtIndex:0]);
*pp1 = CGPointMake(-1.0f, -1.0f);
NSLog(@"%@", NSStringFromCGPoint(*t.p1)); // changed value
Problem: I thought the code this way is correct, with all the bridges and stuff, but it crashes on the inserting to rawPoints, not even getting to the end. Too sad.
Question: Can someone help me understand what I did wrong, and help me make it right so it works in the way I described, perhaps using a different objects or methods?
Thanks!
CGPoint *to a valid ObjC object. you were trying to fool the compiler so it compile your code. but it won't make your code work.