Это в порядке для использования “классического” malloc () / свободный () в приложениях Objective-C/iPhone?

Самое популярное (== стандарт?) способ определить часовой пояс, который я видел вокруг, просто выяснение у самих пользователей. , Если Ваш веб-сайт требует подписки, это могло бы быть сохранено в данных профиля пользователей. Для скоро пользователей даты могли быть отображены как UTC или GMT или некоторые такой.

я не пытаюсь быть самоуверенным типом. Это просто, что иногда некоторые проблемы имеют более прекрасные решения за пределами любого контекста программирования.

54
задан ricardopereira 5 September 2019 в 12:49
поделиться

5 ответов

Есть оболочка Objective-C вокруг необработанной памяти, которую я часто использую для аналогичных задач: NSMutableData . Его преимущество заключается в том, что вы можете сохранить / освободить право собственности, плюс он может легко увеличивать массив (без необходимости выполнять перераспределение самостоятельно).

Ваш код будет выглядеть так:

NSMutableData* data = [NSMutableData dataWithLength:sizeof(int) * 100];
int* array = [data mutableBytes];
// memory is already zeroed

// use the array

// decide later that we need more space:
[data setLength:sizeof(int) * 200];
array = [data mutableBytes]; // re-fetch pointer in case memory needed to be copied

// no need to free
// (it's done when the autoreleased object is deallocated)
80
ответ дан 7 November 2019 в 07:47
поделиться

It's perfectly fine -- Objective-C is a strict superset of C, so if you want to write plain C, there's nothing preventing you from doing so. In many cases, it's advantageous to use malloc and free to avoid the overhead of the Objective-C runtime.

For example, if you need to dynamically allocate an array of an unknown number of integers, it's often simpler and easier:

int *array = malloc(N * sizeof(int));  // check for NULL return value!
// use array[0]..array[N-1]
...
free(array);

Versus:

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:N];
// use NSMutableArray methods to do stuff with array; must use NSNumbers instead
// of plain ints, which adds more overhead
...
[array release];

I was working on a word game for the iPhone, and we had to load a multi-megabyte dictionary of valid words. The word list was loaded into one giant char array allocated with malloc(), with some clever optimizations to reduce the memory size even more. Obviously for something like this, the overhead of using an NSArray is completely impractical on the limited iPhone. I don't know exactly what the overhead is, but it's certainly more than one byte per character.

48
ответ дан 7 November 2019 в 07:47
поделиться

Of course, you can use these functions, because Objective-C is merely a superset of C. However, it is fairly uncommon to do this sort of thing, since Objective-C contains objects and ways to make this easier.

After all, you could write the above code as:

NSMutableArray *array = [[NSMutableArray alloc] init];

//Use the array, adding objects when need be

[array release];

Although you would have to create NSNumber objects to store the ints (since NSArray doesn't allow non-object types to be added), it is generally more common to use objects, because it is easier to move data around, and the array classes are integrated more commonly with other Cocoa classes, and the memory management is generally more straightforward than standard C memory management.

Also, if you start adding or removing objects from the array, then the Cocoa array objects make this much easier to do.

5
ответ дан 7 November 2019 в 07:47
поделиться

If you're dealing with standard C types, it's no less common or "OK" than in C. That's how it's done in C, which is a part of Objective-C.

It's also not unusual to write some kind of object wrapper around these things to bring it into harmony with the rest of Cocoa (KVO, memory management, etc.). So you might create an IntArray class that does the mallocing behind the scenes so you can retain and release it as needed. Note that this isn't strictly necessary — it can just be handy if that kind of structure is a major part of your program.

3
ответ дан 7 November 2019 в 07:47
поделиться

Совершенно нормально использовать malloc и свободно управлять памятью. На самом деле NSObject allocWithZone: использует malloc для получения памяти.

2
ответ дан 7 November 2019 в 07:47
поделиться
Другие вопросы по тегам:

Похожие вопросы: