Главная » Просмотр файлов » Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007

Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 30

Файл №779890 Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books) 30 страницаWiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890) страница 302018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 30)

There are variants of the Copy()method that perform case or accent folding when copying characterdata.• Insert() inserts data into any position, pushing subsequent datatowards the end of the descriptor data area.• Delete() deletes any sequence of data, moving down subsequentdata to close the gap.• Replace() overwrites data in the middle of the descriptor data area.140DESCRIPTORSSubstring MethodsThe TDesC methods Left(), Right(), and Mid() are especiallyapplicable to strings. They let you construct TPtrC descriptors thatrepresent portions of existing descriptor data.

For example, you mighthave a stack descriptor containing text that needs parsing. Following theparse operation you might have a number of TPtrC descriptors, each ofwhich represents syntactically significant parts of the buffer content. Theoriginal descriptor data is not changed, deleted or copied.FormattingTDes::Format() is a bit like sprintf(): it takes a format string anda variable argument list and saves the result in the descriptor.

Methodssuch as AppendFormat() are similar but append the result to existingdescriptor data. Methods such as Format() are implemented in termsof AppendFormat().Many lower-level methods exist to support AppendFormat(): variousNum() methods convert numbers into text and corresponding AppendNum() methods append converted numbers onto an existing descriptor.For simple conversions, the AppendNum() methods are much moreefficient than using AppendFormat() with a suitable format string.In C, scanning methods are provided by sscanf() and packagedvariants such as scanf(), fscanf() and so on. Similar methods areavailable in Symbian OS through TLex and associated classes whichscan data held in descriptors. These methods are relatively specializedand it was not thought appropriate to implement them directly in TDesC.TDesC MethodsAll descriptors are derived from the abstract base class TDesC whichprovides the following methods for accessing the data but doesn’t provideany methods for altering the descriptor contents.NameDescriptionAlloc()AllocL()AllocLC()Creates and returns an HBufC* initializedwith a copy of the descriptor’s data.Compare()CompareF()CompareC()Compares the descriptor’s data with asupplied descriptor.Find()FindC()FindF()Searches for the first occurrence of aspecified data sequence, with the searchbeginning at the start of the descriptor.MANIPULATING DESCRIPTORSName141DescriptionHasPrefixC()Compares a possible prefix against thestart of the descriptor, using a collatedcomparison.Left()Returns a TPtrC representing theleftmost n characters.Length()Returns the length of the data.

Do notconfuse it with Size(). For narrowdescriptors, they return the same value;for wide descriptors, the size is twice thelength.Locate()LocateF()LocateReverse()LocateReverseF()Searches for the first occurrence of acharacter within the descriptor’s data,starting the search from the leftmost orrightmost position.Match()MatchC()MatchF()Searches the descriptor’s data for a matchwith a match pattern supplied in thespecified descriptor.Mid()Returns a TPtrC representing the middlen characters from position m.operator<()operator<=()operator>()operator>=()operator==()operator!=()Returns a TBool indicating the result ofthe comparison between the descriptorand a specified descriptor.operator[]()Returns a const TUint& to a specifiedsingle data item within the descriptordata.

Iterating over a descriptor usingoperator[] is expensive; considerusing C++ pointer arithmetic and theTDesC::Ptr() function instead.142DESCRIPTORSNameDescriptionPtr()Returns a const TUint* to the datarepresented by the descriptor.Right()Returns a TPtrC representing therightmost n characters.Size()Returns the size of the data in bytes; donot confuse it with Length().TDes MethodsDescriptors that derive from TDes are directly modifiable.

TDes providesthe methods to alter the contents of these descriptors, summarized below.NameAppend()DescriptionAppends a character, a descriptor,or data onto the end of thedescriptor.AppendFill()Appends and fills the descriptorwith a specified character.AppendJustify()Appends data and justifies it.AppendFormat()AppendFormatList()Formats and appends text onto theend of the descriptor.AppendNum()AppendNumUC()AppendNumFixedWidth()AppendNumFixedWidthUC()Converts a number into a characterrepresentation or fixed-widthcharacter representation andappends to the end of the descriptor.Capitalize()Capitalizes the content of thedescriptor.Collapse()Narrows each character.MANIPULATING DESCRIPTORSName143DescriptionCollate()Performs collation on the content ofthe descriptor (this method isdeprecated).Copy()CopyC()CopyCP()CopyF()CopyLC()CopyUC()Copies data into the descriptor withvarious options. TDes16::Copy(const TDesC8&) converts from anarrow descriptor to a widedescriptor; with TDes8::Copy(const TDesC16&) eachdouble-byte value can only becopied into the correspondingsingle byte when the double-bytevalue is less than decimal 256.

Adouble-byte value of 256 or greatercannot be copied and thecorrespondingsingle byte is set to a value ofdecimal 1.Delete()Delete n characters of data from thedescriptor starting at position m.Expand()Zero-extends each narrow characterto 16 bits (only available for TDes8and from Symbian OS v8.1)Fill()FillZ()Fills the descriptor with a specifiedTChar or with binary zeros.Fold()Performs folding on the contents ofthe descriptor.Format()FormatList()Formats and copies text into thedescriptor.Insert()Inserts data into the descriptor fromposition n.144NameDESCRIPTORSDescriptionJustify()Copies data into the descriptor andjustifies it, replacing any existingdata.LeftTPtr()Returns a TPtr to the leftmostportion of the descriptor of length n.LowerCase()Converts the contents of thedescriptor to lower case.MaxLength()Returns the maximum length of thedescriptor.MaxSize()Returns the maximum size of thedescriptor.MidTPtr()Returns a TPtr to a portion of thedescriptor starting at position p andof length l.Num()NumUC()NumFixedWidth()NumFixedWidthUC()Converts a number into a characterrepresentation (with fixed width)and copies it to the descriptor.operator=()operator+=()Copies or appends data into thedescriptor.operator[]()operator[]() constReturns a TUint& or const TUint&to a specified data item in thedescriptor.PtrZ()Appends a NULL terminator ontothe end of the descriptor’s data andreturns a pointer to the data; thisallows the pointer to be useddirectly as a C string.

The length ofthe descriptor must be less than itsmaximum length to allow for theaddition of the terminator.MANIPULATING DESCRIPTORSName145DescriptionRepeat()Copies data with repetition into thedescriptor, either from anotherdescriptor or a specified memorylocation.Replace()Replaces data in the descriptor.RightTPtr()Returns a TPtr to the rightmost ncharacters of the descriptor.SetLength()Sets the length of the datarepresented by the descriptor.SetMax()Sets the length of the data to themaximum length of the descriptor.Swap()Swaps the data represented by thedescriptor with the data representedby a specified descriptor.Trim()TrimAll()TrimLeft()TrimRight()Presents various options for deletingwhite space within the descriptor.UpperCase()Converts the contents of thedescriptor to upper caseZero()Sets the length of the data to zero.ZeroTerminate()Appends a zero terminator onto theend of this descriptor’s data.HBufC MethodsNameDescriptionDes()Creates and returns a modifiable pointerdescriptor (TPtr) for the data represented bythe descriptor, thus allowing modification.146DESCRIPTORSNameDescriptionNew()NewL()NewLC()NewMax()NewMaxL()NewMaxLC()Creates an empty HBufC and returns a pointerto it.

With New(), NewL() and NewLC(),the length of the data is set to 0; while withNewMax(), NewMaxL() and NewMaxLC(),the length is set to the maximum length thatwas passed as a parameter.NewL()NewLC()Creates an HBufC and internalize data into itfrom a specified RReadStream beforereturning a pointer to it.ReAlloc()ReAllocL()Creates and returns a new HBufC* which isan expansion or contraction of theoriginal.operator=()Copies data into the descriptor, replacing anyexisting data.RBuf MethodsNameAssign()DescriptionAssigns or transfers ownership of anHBufC*, a specified memorylocation, or another RBuf to thedescriptor.CleanupClosePushL()Pushes an instance of the RBuf to thecleanup stack.Close()Frees any allocated memory ownedby the RBuf.Create()CreateL()CreateMax()CreateMaxL()Creates the descriptor, allocatingsufficient memory to contain the dataup to a specified length.

Overloadsexist to assign data to the descriptorfrom various specified sourcesincluding an RReadStream.operator=()Assignment operator.MANIPULATING DESCRIPTORSName147DescriptionRBuf()Creates the descriptor, optionallytransferring ownership from a specifiedHBufC*.ReAlloc()ReAllocL()Resizes the memory holding thedescriptor data.Swap()Swaps the contents of the descriptorwith another RBuf.TBuf MethodsNameDescriptionTBuf()Various options for creating a TBufC.operator=()Various options for assignment to thedescriptor.TBufC MethodsNameDescriptionTBufC()Various options for creating a TBuf.operator=()Various options for assignment to thedescriptor.Des()Creates and returns a modifiabledescriptor (TPtr) to the data, allowing ameans of altering it.TPtr MethodsNameoperator=()DescriptionVarious options for copying data intothe descriptor.

This operator does not dowhat you might expect for a standardC++ assignment operator (seeSection 5.7).148NameTPtr()Set()DESCRIPTORSDescriptionConstructs the descriptor from data in aspecified location in memory.Sets the descriptor to an existingdescriptor or to a specified memorylocation (which may be in ROM orRAM).TPtrC MethodsNameTPtrC()Set()DescriptionConstructs the descriptor from anotherdescriptor or from data in a specifiedlocation in memory.Sets the descriptor to an existingdescriptor or to a specified memorylocation (which may be in ROM orRAM).SummaryIn this chapter we’ve seen how Symbian OS handles strings and binarydata using descriptors.

We covered a lot of material and there is much toremember. The main summary points are:• descriptors are used for storing both string and binary data• use the _LIT macro to store data in the program binary• use a TBuf or TBufC when you need to construct a descriptor, use itand discard it, provided that the maximum size is not too large• use a TPtrC when you need to get a substring of another descriptoror when you need to pass data, not in the form of a descriptor, to amethod expecting a descriptor• use a TPtr when you want to modify a TBufC, HBufC or some rawdata as though it were a descriptor• use a TPtrC or TPtr when you need to refer to raw data or anexisting descriptorSUMMARY149• use an HBufC or RBuf when the length of the descriptor is unknownat compile time or when the maximum length is large• use const TDesC& and TDes& to pass descriptors to methods• use const TDesC&, TDes&, TPtr or HBufC* to return descriptorsfrom methods.6Active ObjectsIn the past, programs were written so that, every so often, the programwould decide to check for user input and would then process it.

Essentiallythe application would poll to see if the user had initiated an action andthen respond by carrying out some task. However, with modern GUIsystems, the user is in control – their input is the focus of the application’sexistence. In this paradigm, the application can be thought of as beingevent-driven – it is always waiting for the user to interact with the deviceand then carries out some operation in response to that interaction.In GUI systems, application programs spend the majority of theirtime waiting for events, for example, keyboard input, pointer input,completion of an I/O request, timer events, etc. These events and theservices associated with them are provided by asynchronous serviceproviders. Application programs then simply respond to these events.Symbian OS provides some fundamental building blocks for eventhandling systems, known as active objects.

Характеристики

Тип файла
PDF-файл
Размер
6,45 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6374
Авторов
на СтудИзбе
309
Средний доход
с одного платного файла
Обучение Подробнее