سؤال

In my program, I store objective-c objects in a c array, like this

va_start(list, o);
retval->objs = malloc(SIZE * count);
retval->objs[0] = (__bridge void *)o;
for (int i = 1; i < count; i++)
{
    id o = va_arg(list, id);
    retval->objs[i] = (__bridge void *)o;
}
va_end(list);

(count is a number containing how many objects will be added; that value is always correct)

objs is a void ** and is part of retval, which is a pointer to a struct. As of now, SIZE is defined as 100. Increasing and decreasing that had no effect.

As you can see, I bridge o to a void *, as I have to. objs, when all the objects are added, contains 3 objective-c objects. When I try to access a value like this

void *obj = CLArrayObjectAtIndex(_arr, ind);
return (__bridge id)obj;

this is the CLArrayObjectAtIndex() function

void *CLArrayObjectAtIndex(CLArrayType *arr, int ind)
{
    void *o = arr->objs[ind];
    if (o)
        return o;
    else
        perror("Attempt to access NULL object or index out of bounds."), abort();
}

if the index (ind) is 0, it works. If the index is 1, the program crashes when it returns in main. If the index is 2, the program crashes as soon as I try to access it. If the index is 1, the value returned above is correct, but when the program crashes on return it is nil.

If the index is 1, the EXC_BAD_ACCESS code is 1; if the index is 2, the code is EXC_I386_GPFLT, a general protection fault. I already checked here for an explanation of this exception, although I couldn't find anything helpful. So, does anybody see why this error may be occurring?

هل كانت مفيدة؟

المحلول

when you store obj-c objects in C array don't just bridge cast them since that way arc doesn't know they are still used and releases them. __bridge_retain them so they stay around later, when you free the array __bridge_transfer them to give them back to ARC

also don't define size as 100.. sizeof(id) should work. You only need to store pointers

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top